ReactJs: How to pass the initial state while rendering a component?

后端 未结 4 1941
情深已故
情深已故 2020-12-16 12:53

I know I can pass props while rendering a component. I\'m also aware of the getInitialState method. But the problem is, getInitialState

4条回答
  •  执念已碎
    2020-12-16 13:28

    To quote the React docs:

    Using props, passed down from parent, to generate state in getInitialState often leads to duplication of "source of truth", i.e. where the real data is. Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble

    And:

    However, it's not an anti-pattern if you make it clear that synchronization's not the goal here

    So if your props include a value and an initialValue, then it's clear that the latter is for initialization, and there's no confusion.

    See the React docs for code examples.

提交回复
热议问题