class IssueRecordUpload extends React.Component {
constructor(props) {
super(props)
this.state = {
filters: {},
}
}
static propTypes = {
filters: PropTypes.object,
dispatch: PropTypes.func
}
componentDidMount() {
const {filters} = this.props
this.setState({
filters: filters
}, () => {
this.load()
})
}
componentWillReceiveProps(next) {
const {filters} = this.state // filters = undefined
if (filters.toString() !== next.filters.toString()) {
this.setState({
filters: next.filters,
}, () => {
this.load()
})
}
}
load = () => {
const {dispatch} = this.props
const {filters} = this.state
dispatch(filters)
}
}
filters和dispatch是父组件传进来的,DidMount的时候setState() props.filter -> state.filters,在WillReceiveProps中再接收新的props,发现原有state.filters为undefined,并且setState失败,但是next.filters是存在的,求解是什么原因。谢谢大佬!
先答题:
就你目前这些代码来看,问题应该在
componentDidMount
中。因为在
constructor
中this.state.filters
是一个空对象,当走过componentDidMount
后,在componentWillReceiveProps
取值时却成了undefined
,那么很可能是你在componentDidMount
执行this.setState({ filters: filters })
时,filters
变量,也就是this.props.filters
的值就是undefined
。提几点个人看法,可供参考:
componentDidMount
时从this.props
上取值并赋值给this.state
呢,在我看来,这一步完全可以放到constructor
中去做。load
方法就你目前这些代码来看,不应该放在你的IssueRecordUpload
组件上,而应该放到父组件中去处理,并将处理好的filters
交给IssueRecordUpload
就好了。