我正在使用 react.js
、redux
和 redux-modal
。我想在显示模式时执行代码。
当我将代码放入 componentWillMount
中时,它只会在第一次执行。
componentWillMount() {
// Just execute one time
// Do something
}
redux-modal
使用 show
状态变量来显示或隐藏模态,因此我使用以下代码来处理显示事件:
componentWillReceiveProps(nextProps) {
// When modal is shown
if (!this.props.show && nextProps.show) {
// Do something
}
}
除了第一次安装模态之外,它运行良好。
现在我使用 componentWillMount
和 componentWillReceiveProps
一起处理模态显示事件。
有没有更好的解决方案来处理模态显示事件?
最佳答案
您可以简单地将代码放入渲染函数中,如下所示:
render() {
{(this.props.show) ? <MyModalComponent/> : null}
... // other components to render
}
如果您使用 componentDidMount()
来触发 API 调用,则使用上述代码,您的流程将是:
- 第一次渲染:
this.props.show == false
render()
运行,组件将在没有模态的情况下渲染componentDidMount()
运行,这会触发 API 调用- API 调用结果更新存储,将
show
设置为 true - 商店更新触发新的渲染周期
- 下一个渲染周期:
this.props.show == true
render()
运行,组件将以模态方式渲染- (
componentDidMount()
未运行,因为这是第二次渲染)
关于javascript - 当 React.js 中显示模态时如何处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37019312/