我是 React/Redux 的新手,状态有问题。
轨迹容器.jsx
class TrajectContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
trajects: props.trajects,
onClick: props.onClick
};
}
componentWillReceiveProps(nextProps) {
console.log('componentWillReceiveProps', nextProps);
this.setState(nextProps);
}
render() {
// When the componentWillReceiveProps is not present, the this.state will hold the old state
console.log('rerender', this.state);
return (<div className="col-md-6">
<h2>Trajects</h2>
<button className="btn btn-primary" onClick={this.state.onClick}>Add new Traject</button>
{this.state.trajects.map(traject => <Traject traject={traject} key={traject.name}/>)}
</div>)
}
}
const mapStateToProps = function (store) {
console.log('mapToStateProps', store);
return {
trajects: store.trajects
};
};
const mapDispatchToProps = function (dispatch, ownProps) {
return {
onClick: function () {
dispatch(addTraject());
}
}
};
export default connect(mapStateToProps, mapDispatchToProps)(TrajectContainer);
当 reducer 返回新状态时,组件将使用新数据重新渲染。
但是:如果我删除 componentWillReceiveProps 函数,则 render() 函数具有旧状态。
我检查了在 mapStateToProps 中收到的数据,这是新的新状态。所以我不明白为什么我需要 componentWillReceiveProps 函数才能让渲染函数接收新数据。
难道我做错了什么?
原文由 Mazzy 发布,翻译遵循 CC BY-SA 4.0 许可协议
componentWillReceiveProps
如果你想用新的道具值更新状态值是必需的,只要道具值发生任何变化,这个方法就会被调用。因为您将道具值存储在状态变量中,并像这样使用它:
this.state.KeyName
这就是为什么你需要
componentWillReceiveProps
生命周期方法来用新的 props 值更新状态值,只有组件的 props 值会被更新,但 状态不会自动更新。如果您不更新状态,那么this.state
将始终具有初始数据。componentWillReceiveProps
如果您不将 props 值存储在 state 中并直接使用,则不需要:this.props.keyName
现在 react 将始终在 render 方法中使用更新的 props 值,如果 props 发生任何变化,它将使用新的 props 重新渲染组件。
根据 文档:
建议:
不要将 props 值存储在 state 中,直接使用
this.props
并创建 ui 组件。