對於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
。它应该根据当前的状态和属性返回下一个状态。请至少仔细阅读文档。 - trixn