【发布时间】:2019-07-13 19:02:45
【问题描述】:
我在互联网上读到执行以下操作是一种糟糕的编码习惯:
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。
干杯。
【问题讨论】:
-
直接使用道具即可。为什么要复制到状态? componentWillReceiveProps 也被贬值了。
-
@johnnypeter 我知道,我正在使用 React 15,这就是它仍然可用的原因。如前所述,如果我依赖 componentWillReceiveProps() 方法,它只会运行一次。当我离开并返回页面时,它不会运行,我的本地状态也不会更新。
-
应该有一个单一的事实来源,无论是 prop 还是 state,如果您想在第一次挂载时使用 props 初始化 state,然后将其留给组件,则可以在构造函数中将 prop 分配给 state
-
是的,Rahul,但我读过文章说将其初始化为状态并不好。所以我在这里很困惑
标签: javascript reactjs redux state react-props