【问题标题】:about the state of react redux关于 react redux 的状态
【发布时间】: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


【解决方案1】:

我从您的帖子中了解到,您想知道为什么您无法在 componentDidMount() 中看到状态更新的反映。

这是因为 componentDidMount 函数是在创建 react 组件的实例并将其插入 DOM 时调用的。它在反应组件生命周期的安装阶段被调用。

为了能够看到您对 redux 状态更新的反映,您需要使用在更新阶段调用的函数,例如:

  • componentWillReceiveProps()
  • componentDidUpdate()
  • shouldComponentUpdate()

要获取更多详细信息,请查看组件生命周期文档:

https://facebook.github.io/react/docs/react-component.html

【讨论】:

    猜你喜欢
    • 2021-08-04
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 2020-10-26
    • 2019-05-30
    相关资源
    最近更新 更多