在组件中
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)
生命周期相同。如果我删除它们,这会带来更好的做法吗?
答案 0 :(得分:1)
Redux使得不需要使用本地状态。如果全局状态和局部状态影响相同的实体(在这种情况下为errors
),则是不必要的。
由于CreateProfile
只是无状态容器,因此应在当前使用this.props.errors
的任何地方(而不是在原始代码中的任何地方)使用this.state.error
。
componentWillReceiveProps
已过时,在这里没有任何用处,因为它将errors
映射到其自身。如果需要防止不必要的更新,可以将CreateProfile
做成纯组件。