我是否必须将道具放置在构造函数中,因为它们位于mapStateToProps中?

时间:2019-02-06 12:20:36

标签: reactjs

在组件中

import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ProfileForm from '../common/ProfileForm';
import { createProfile } from '../../actions/profileActions';
import { withRouter } from 'react-router-dom';

class CreateProfile extends Component {
    constructor(props) {
        super(props);

        this.state = {
            errors: {}
        };

        this.onSubmit = this.onSubmit.bind(this);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.errors) {
            this.setState({ errors: nextProps.errors });
        }
    }

    onSubmit(profileData) {
        this.props.createProfile(profileData, this.props.history);
    }

    render() {
        return <ProfileForm errors={this.props.errors} onSubmit={this.onSubmit} />
    }
}

CreateProfile.propTypes = {
    errors: PropTypes.object.isRequired,
    createProfile: PropTypes.func.isRequired
};

const mapStateToProps = (state) => ({
    errors: state.errors
});

export default connect(mapStateToProps, { createProfile })(withRouter(CreateProfile));

我在构造函数中设置了道具errors,但是我需要这样做吗?道具errors未在组件中使用,仅传递给子表单组件ProfileForm。从errors方法返回errors时,createProfile()被发送到应用商店。

componentWillReceiveProps(nextProps)生命周期相同。如果我删除它们,这会带来更好的做法吗?

1 个答案:

答案 0 :(得分:1)

Redux使得不需要使用本地状态。如果全局状态和局部状态影响相同的实体(在这种情况下为errors),则是不必要的。

由于CreateProfile只是无状态容器,因此应在当前使用this.props.errors的任何地方(而不是在原始代码中的任何地方)使用this.state.error

componentWillReceiveProps已过时,在这里没有任何用处,因为它将errors映射到其自身。如果需要防止不必要的更新,可以将CreateProfile做成纯组件。