我是否可以始终使用this.props从操作中调用函数?

时间:2017-06-26 10:10:15

标签: redux react-redux

我正在做一个Redux教程,并且不了解其中的一些内容。我有以下容器:

import React, { Component } from 'react';
import CommentsList from "./comments_list";
import { connect } from 'react-redux';
import * as actions from '../actions';

class CommentBox extends Component {
    constructor(props) {
        super(props);
        this.state = { comment: '' };
    }
    handleChange(event) {
        this.setState({ comment: event.target.value })
    }

    submitButton(e) {
        e.preventDefault();
        this.props.saveComment(this.state.comment);
        this.setState({ comment: '' });
    }

    render () {
        return(
            <div>
                <form onSubmit={(e) => this.submitButton(e)} className="comment-box">
                    <textarea
                        value={this.state.comment}
                        onChange={(e) => this.handleChange(e)} />
                    <button action="submit">Submit</button>
                </form>
                <CommentsList comment={this.state.comment}/>
            </div>
        );
    }
}

export default connect(null, actions)(CommentBox);

此容器使用:

import * as actions from '../actions';

并在文件的底部:

export default connect(null, actions)(CommentBox);

我以前习惯使用mapStateToProps和mapDispatchToProps,但这里只导入动作,然后在submitButton(e)方法中使用:

this.props.saveComment(this.state.comment);

saveComment来自actions / index.js文件:

import { SAVE_COMMENT } from './types';

export function saveComment(comment) {
    return {
        type: SAVE_COMMENT,
        payload: comment
    }
}

我是否可以始终使用this.props从actions / index.js文件中调用函数?为什么我不首先使用mapStateToProps?

1 个答案:

答案 0 :(得分:2)

  

我是否可以始终使用this.props从actions / index.js文件中调用函数?

是。来自react-redux docs

  

[mapDispatchToProps(dispatch, [ownProps]): dispatchProps](对象或函数):如果传递了一个对象,则假定其中的每个函数都是一个Redux动作创建者。具有相同函数名称的对象,但每个动作创建者都包含在一个调度调用中,因此可以直接调用它们,它们将合并到组件的道具中。

connect正在为您actions/index.js打包导出dispatch。{/ p>

  

为什么我不需要先使用mapStateToProps?

因为mapStateToPropsmapDispatchToProps用于不同目的,并在合并并注入组件之前单独映射。

如果返回undefinednull,则会被忽略。在mapStateToProps的情况下,它还意味着组件不会从商店订阅更新。同样,来自react-redux docs

  

如果您不想订阅商店更新,请传递null或undefined代替mapStateToProps。

相关问题