gpt4 book ai didi

javascript - React - getDerivedStateFromProps 是否需要返回所有状态属性?

转载 作者:行者123 更新时间:2023-11-29 15:13:57 24 4
gpt4 key购买 nike

在 React 组件中使用 getDerivedStateFromProps 生命周期方法时,返回的状态是完全覆盖组件的现有状态,还是只是更新返回的特定状态属性?例如,

class foo extends Component {
constructor() {
this.state = {
one: true,
two: false,
}
}

getDerivedStateFromProps(props, state) {
...
return {
one: false,
}
}

...
}

状态会是:

{ one: false }

{
one: false,
two: false,
}

?

最佳答案

它将更新您返回的对象中存在的状态片段,并保持其他状态不变,as it is stated in the documentation :

getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

示例

class App extends React.Component {
state = { one: 1 };

static getDerivedStateFromProps() {
return { two: 2 };
}

render() {
return <div>{JSON.stringify(this.state)}</div>;
}
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://unpkg.com/react@16.4.1/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16.4.1/umd/react-dom.production.min.js"></script>

<div id="root"></div>

关于javascript - React - getDerivedStateFromProps 是否需要返回所有状态属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51316068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com