【发布时间】:2017-08-18 20:09:26
【问题描述】:
我正在使用 Redux 编写一个 SPA 来管理我的状态。有一个逻辑组件连接到 redux 存储,它有一个子组件,它通过 props 将“posts”状态传输到子组件。在子组件的渲染函数中:
const {onShow,posts} = this.props;
效果很好;只是帖子会随着 redux 商店的变化而变化。但是在它的componentDidMount()函数或构造函数中,帖子不会随着redux store而改变,那怎么会发生呢?
componentDidMount(){
const {posts} = this.props;
console.log(posts)
}
这里是完整的组件code。这是关于 Lists 组件和 Posts 组件的。
【问题讨论】:
-
你可以通过
componentWillReceiveProps(nextProps) { console.log(nextProps.posts }获得新的道具 -
对对对,就是不知道为什么componentDidMount函数里的帖子不会变,
-
componentDidMount 不会在 props 更改时触发,它只会在初始渲染时触发。facebook.github.io/react/docs/react-component.html
-
因为
componentDidMount()仅在组件被...mounted(即,渲染到 UI)时触发。或者这就是我的解释。 -
react router navigate 会重新挂载父逻辑组件,然后子逻辑组件也会重新挂载。并且 componentDidMount 确实再次运行。
标签: javascript reactjs redux