【问题标题】:Why official doc recommend to use componentDidMount instead of callback in setState?为什么官方文档建议在 setState 中使用 componentDidMount 而不是回调?
【发布时间】:2017-08-09 10:08:47
【问题描述】:

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

我好像官方文档说:

setState() 的第二个参数是一个可选的回调函数,一旦 setState 完成并重新渲染组件,就会执行该回调函数。通常我们建议使用 componentDidUpdate() 来代替此类逻辑。

当我们需要使用最新状态时,为什么他们建议使用 componentDidUpdate 而不是回调?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    componentDidUpdate 也会在每次更新发生后立即调用。此时,最新状态已更新。

    将所有检查状态逻辑放在componentDidUpdate 中比许多callback 更容易管理每个setState

    顺便说一句,如果您使用redux,我们不会在您的组件中使用setStateMore about redux

    注意:初始渲染不调用componentDidUpdate

    了解更多组件生命周期https://facebook.github.io/react/docs/react-component.html#componentdidupdate

    【讨论】:

    • 总之,把逻辑放在componentDidUpdate里面比较好管。
    • 但是我不同意你的下一点,如果我使用redux,我不应该使用setState。我还是觉得如果状态只是为了改变UI,我们可以用setState来处理,而不是把所有的数据都放在redux里,再传给很多层组件。
    • 是否使用 redux 取决于您的应用程序有多大。那篇文章对你有用medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367
    • 我最近发布了类似的问题。 stackoverflow.com/questions/71504483/…
    猜你喜欢
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 2014-07-03
    • 2016-04-09
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    相关资源
    最近更新 更多