使用React useState()钩子更新和合并状态对象 [英] Updating and merging state object using React useState() hook

查看:598
本文介绍了使用React useState()钩子更新和合并状态对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这两个React Hooks文档有些混乱.使用状态挂钩更新状态对象的最佳做法是哪种?

I'm finding these two pieces of the React Hooks docs a little confusing. Which one is the best practice for updating a state object using the state hook?

想象一下要进行以下状态更新:

Imagine a want to make the following state update:

INITIAL_STATE = {
  propA: true,
  propB: true
}

stateAfter = {
  propA: true,
  propB: false   // Changing this property
}

选项1

使用React Hook 文章中,我们可以做到这一点:

From the Using the React Hook article, we get that this is possible:

const [count, setCount] = useState(0);
setCount(count + 1);

所以我可以做:

const [myState, setMyState] = useState(INITIAL_STATE);

然后:

setMyState({
  ...myState,
  propB: false
});

选项2

Hooks Reference 中我们可以得出:

与在类组件中找到的setState方法不同,useState可以 不会自动合并更新对象.您可以复制此 通过将功能更新程序形式与对象传播相结合来实现行为 语法:

Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});

据我所知,两者都有效.那么区别是什么呢?最佳做法是哪一种?我应该使用传递函数(选项2)来访问先前的状态,还是应该简单地使用扩展语法来访问当前状态(选项1)?

As far as I know, both works. So, what is the difference? Which one is the best practice? Should I use pass the function (OPTION 2) to access the previous state, or should I simply access the current state with spread syntax (OPTION 1)?

推荐答案

两个选项都是有效的,但是就像在类组件中使用setState一样,在更新从已经存在的状态中派生的状态时,也需要小心.

Both options are valid, but just as with setState in a class component you need to be careful when updating state derived from something that already is in state.

例如连续两次更新计数,如果不使用更新状态的函数版本,它将无法按预期工作.

If you e.g. update a count twice in a row, it will not work as expected if you don't use the function version of updating the state.

const { useState } = React;

function App() {
  const [count, setCount] = useState(0);

  function brokenIncrement() {
    setCount(count + 1);
    setCount(count + 1);
  }

  function increment() {
    setCount(count => count + 1);
    setCount(count => count + 1);
  }

  return (
    <div>
      <div>{count}</div>
      <button onClick={brokenIncrement}>Broken increment</button>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));

<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

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

这篇关于使用React useState()钩子更新和合并状态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆