【发布时间】:2018-02-17 04:15:32
【问题描述】:
我是 React/Redux 的新手,遇到了状态问题。
TrajectContainer.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 中收到的数据,这是新的 New State。 所以我不明白为什么我需要 componentWillReceiveProps 函数才能让渲染函数接收新数据。
我做错了吗?
【问题讨论】:
-
您不需要
state来处理这些更改。trajects属于state和props(来自redux 的connect)。此外,在每个componentWillReceiveProps上设置状态不是一个好习惯。我会从状态中删除trajects并仅使用传入的道具。它们会在必要时更改,您将始终拥有最新的值。 -
@HemersonCarlin 这就是我想要的,但是 render() 中的状态不是从 mapStateToProps 传递的最新状态,这是我的问题。我只有在使用 .setState 时才获得新状态,这就是我制作这个 StackOverflow Q 的原因!
-
尝试删除状态并改用
this.props.trajects。
标签: reactjs react-redux