【发布时间】:2021-12-06 17:49:35
【问题描述】:
在 react docs 的文章 (https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html) 中,有以下内容:
Refs 在某些情况下(例如这种情况)很有用,但通常我们建议您谨慎使用它们。即使在演示中,这种命令式方法也不理想,因为会发生两次渲染而不是一次。。
这是来自https://codesandbox.io/s/l70krvpykl?file=/index.js的演示的相关部分:
handleChange = index => {
this.setState({ selectedIndex: index }, () => {
const selectedAccount = this.props.accounts[index];
this.inputRef.current.resetEmailForNewUser(selectedAccount.email);
});
};
我调整了这个演示,我想出了一种方法来重新渲染一次(我删除了回调函数,因为它在 componentDidUpdate 之后运行,所以它会导致重新渲染两次):
handleChange = index => {
this.setState({ selectedIndex: index }); // set state of Parent Component (itself)
const selectedAccount = this.props.accounts[index];
this.inputRef.current.resetEmailForNewUser(selectedAccount.email); // set State of Child Component
};
我想知道为什么这有效并且只重新渲染一次。我想可能会同时对 setState 做出反应。
我不知道为什么不建议这样做?
【问题讨论】:
标签: reactjs