与之前 getDerivedStateFromProps 中的 props 进行比较 [英] Compare with previous props in getDerivedStateFromProps
问题描述
想想一个组件,它有一个 prop 'name' 和 state 'elapse'.
Think of a component that has a prop 'name' and state 'elapse'.
new Component(name) => "Hi {name}. It's been {elapse} seconds"
{elapse}
应该在 prop {name}
更改时重置为 0.
{elapse}
should be reset to 0 when the prop {name}
changes.
如果道具在 10 秒时从Alice"变为Bob",消息应该从
If the prop changes from 'Alice' to 'Bob' at 10 seconds, the message should change from
爱丽丝.已经过了 10 秒
Hi Alice. It's been 10 seconds
到
嗨鲍勃.已经 0 秒了
Hi Bob. It's been 0 seconds
getDerivedStateFromProps
无法使用,因为{elapse}
不是{name}
的纯函数,我不能返回0因为它可能会在重新渲染时调用.getDerivedStateFromProps
cannot be used because{elapse}
is not a pure function of{name}
, and I cannot return 0 because it may be called on re-render.componentDidUpdate
最终会将{elapse}
更新为 0,但在此之前,无效状态 Hi Bob. It's been 0 seconds" 显示给用户.componentDidUpdate
will eventually update{elapse}
to 0, but before that, the invalid state "Hi Bob. It's been 0 seconds" is shown to the user.getDerivedStateFromProps
或componentDidUpdate
能否实现这个场景?Can
getDerivedStateFromProps
orcomponentDidUpdate
implement this scenario?在许多情况下,状态不是道具的纯粹功能.
getDerivedStateFromProps
仅用于无状态功能组件吗?React 是否鼓励使用无状态组件?
In many cases the state is not a pure function of props. Is
getDerivedStateFromProps
only for stateless functional components? Does react encourage the use of stateless components?
getDerivedStateFromProps
如何替换有状态组件中的componentWillReceiveProps
?How can
getDerivedStateFromProps
replacecomponentWillReceiveProps
in stateful components?推荐答案
如果你环顾四周,你会发现你不是第一个遇到这个问题的人 - 它在 github 上进行了彻底的讨论 1 2 3 和hackernews 上的一个帖子此处.推荐的解决方案是在 state 中镜像你需要检查的 props:
If you look around you'll see you're not the first one having this problem - it was thoroughly discussed on github 1 2 3 and in a thread on hackernews here. The recommended solution is to mirror the props you need to check in the state:
state = { name: "", lastTime: Date.now() } static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.name !== prevState.name) { return { name: nextProps.name, lastTime: Date.now() }; } return null; }
这篇关于与之前 getDerivedStateFromProps 中的 props 进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!