【发布时间】:2018-08-03 11:26:08
【问题描述】:
componentWillReceiveProps 和 getDerivedStateFromProps 到底是什么对我来说是个微妙的问题。因为,我在使用 getDerivedStateFromProps 时遇到了一个问题:
// Component
state = {
myState: []
}
// Using this method works fine:
componentWillReceiveProps(nextProps) {
this.setState({
myState: nextProps.myPropsState
})
}
// But using this method will cause the checkboxes to be readonly:
static getDerivedStateFromProps(nextProps,prevProps) {
const { myPropsState: myState } = nextProps
return {
myState
}
}
// And here's checkbox
<input type="checkbox" id={`someid`}
onChange={(e) => this.handleMethod(e, comp.myState)}
checked={myState.indexOf(comp.myState) > -1} />
React 版本:16.4.1
【问题讨论】:
-
传递给
getDerivedStateFromProps ()的参数是当前的props和state,而不是nextProps和prevProps。它应该根据当前状态和道具返回下一个状态。请至少仔细阅读文档。 -
这里不重要,参数名称可以是我们希望的任何名称,但我只是写了比较会收到道具。此外,我在这里解释为什么当我使用派生状态时复选框是只读的?
-
如何通过将参数命名为它们不代表的东西来比较它们?还有unconditionally updating state from props is considered an anti-pattern.
标签: javascript reactjs lifecycle