ReactJS componentWillReceiveProps 不触发
ReactJS componentWillReceiveProps not triggering
我正在实施 https://github.com/akiran/react-slick
的滑块
我有自定义的子组件,需要在父组件更新时更新它们的状态。当我正常加载幻灯片时,例如:
<Slider ref={c => this.slider = c } {...settings}>
<div key={1}>
<Slide1 key={1} formData={this.state.formData} />
</div>
...
</Slider>
componentWillReceiveProps 工作正常。但是,当我根据示例 here 动态加载幻灯片时,这些生命周期事件永远不会被调用,即使在父级中更新状态之后也是如此。
componentDidMount() {
this.setState({
slides: [
<div key={1}>
<Slide1 key={1} formData={this.state.formData} />
</div>,
....
]
)};
}
<Slider ref={c => this.slider = c } {...settings}>
{this.state.slides.map(function (slide, i) {
return slide
})}
</Slide>
像这样加载组件时,componentWillReceiveProps 永远不会被调用,即使在状态更新之后也是如此。
我错过了什么?我不需要 Redux 来管理这个,对吗?
首先,尝试在状态中存储实际的 React 元素是一个非常糟糕的主意,您应该只存储纯数据,然后在 render
方法中使用这些数据来组成标记。
其次,componentWillReceiveProps
在你的情况下没有被调用,因为你的 Slide1 是第一次在那里呈现,它们被安装到 DOM,但是 componentWillReceiveProps
可以仅针对已安装的组件调用,请参阅 documentation.
我正在实施 https://github.com/akiran/react-slick
的滑块我有自定义的子组件,需要在父组件更新时更新它们的状态。当我正常加载幻灯片时,例如:
<Slider ref={c => this.slider = c } {...settings}>
<div key={1}>
<Slide1 key={1} formData={this.state.formData} />
</div>
...
</Slider>
componentWillReceiveProps 工作正常。但是,当我根据示例 here 动态加载幻灯片时,这些生命周期事件永远不会被调用,即使在父级中更新状态之后也是如此。
componentDidMount() {
this.setState({
slides: [
<div key={1}>
<Slide1 key={1} formData={this.state.formData} />
</div>,
....
]
)};
}
<Slider ref={c => this.slider = c } {...settings}>
{this.state.slides.map(function (slide, i) {
return slide
})}
</Slide>
像这样加载组件时,componentWillReceiveProps 永远不会被调用,即使在状态更新之后也是如此。
我错过了什么?我不需要 Redux 来管理这个,对吗?
首先,尝试在状态中存储实际的 React 元素是一个非常糟糕的主意,您应该只存储纯数据,然后在 render
方法中使用这些数据来组成标记。
其次,componentWillReceiveProps
在你的情况下没有被调用,因为你的 Slide1 是第一次在那里呈现,它们被安装到 DOM,但是 componentWillReceiveProps
可以仅针对已安装的组件调用,请参阅 documentation.