我在互联网上读到,执行以下操作是一种糟糕的编码实践:
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
someItem = props.someItem
};
}
}
但是,如果我遇到这种情况:
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
someItem = this.props.someItem
};
}
}
Test.propTypes = {
someItem: PropTypes.array
};
function mapStateToProps(state, ownProps) {
[...]
return {
someItem: someItem
};
}
export default withRouter(connect(mapStateToProps)(Test));
会有问题吗?在网上找不到任何地方不说我不能这样做。
我试图确保每次我导航回该组件时,该组件都能够从 Redux Store 获取数据。我尝试使用 componentWillReceiveProps(),但到目前为止它只运行一次,并且 componentDidMount 和 componentWillMount 不接受 setState。
干杯。
最佳答案
您不应该将 Prop 保存在状态中,除非您希望稍后在本地修改它,并在对 Prop 提供者执行某些操作后更新它。简而言之,您声明不得在代码中的所有时间点直接从 props 派生。
即使你使用 redux mapStateToProps 向组件提供 props,它仍然与来自父组件相同
class Test extends React.Component {
render() {
console.log(this.props.someItem);
}
}
Test.propTypes = {
someItem: PropTypes.array
};
function mapStateToProps(state, ownProps) {
[...]
return {
someItem: someItem
};
}
export default withRouter(connect(mapStateToProps)(Test));
关于javascript - 将 Props 绑定(bind)到 State ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54780423/