<CategorySelector
categoryId={ this.state.categoryId }
parentCategoryId={ this.state.parentCategoryId }
onCategoryChange={(categoryId, parentCategoryId) => this.onCategoryChange(categoryId,parentCategoryId)}/>
这是一个自定义的分类选择器组件,
他的categoryId和parentCategoryId都是从父组件的state中获取的, 获取的就是默认值
如果父组件通过异步请求获取数据,修改了state里面的categoryId和parentCategoryId
子组件通过this.props是获取不到新值的,它还是原来的默认值
想要获取新的categoryId和parentCategoryId,可以借助componentWillReceiveProps生命周期函数
在子组件的代码category-selector.js中:
componentWillReceiveProps (nextProps) {
console.log(nextProps) // 有新传入的值, 就是更新后的值,我们需要的值
console.log(this.props.categoryId, this.props.parentCategoryId) // 还是默认的值
}