简体   繁体   English

使用 React useState hook 设置多个 state 值

[英]Set multiple state values with React useState hook

I would like to set multiple state values with React useState hook, so that I can I update them separately with useEffect hook.我想使用 React useState 挂钩设置多个 state 值,以便我可以使用 useEffect 挂钩单独更新它们。 I have the following code:我有以下代码:

import React, { useState } from "react";

const initialValues = {
  phone: "",
  email: ""
};

const App = () => {
  const [order, setOrder] = useState("");
  const [paid, setPaid] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(initialValues);

  return (
    <div className="App">
    </div>
  );
};

export default App;

But when I inspect the App with React DevTools, I see multiple "State" values for my hook, instead of "order", "paid", "submitting" etc.但是当我使用 React DevTools 检查应用程序时,我看到我的钩子有多个“状态”值,而不是“订单”、“支付”、“提交”等。

Here is the link to my codesandbox .这是我的代码框的链接。

Where is my mistake?我的错误在哪里? How can I set multiple state values to update them separately later on?如何设置多个 state 值以便稍后单独更新它们?

You can make one state with useState hook and put every value there like this.您可以使用useState钩子制作一个 state 并将每个值都放在那里。

import React, { useState } from "react";

const initialValues = {
  phone: "",
  email: ""
};

const App = () => {
  const [state, setState] = useState({
     order:'',
     paid: false,
     submitting: false,
     loading: false,
     data: initialValues
  });
  // example of setting this kind of state
  const sampleChanger = () => {
     setState({...state, paid: true, order: 'sample'});
  }
// etc...

There is nothing wrong with your solution.您的解决方案没有任何问题。 The name you give to those states is only local to your component when you destructure the array that useState returns.当您解构 useState 返回的数组时,您为这些状态指定的名称仅对您的组件是本地的。 React does not know about the name you give to those elements in the array that useState returns. React 不知道你给 useState 返回的数组中的那些元素起什么名字。 Don't worry about the generic name that shows up in dev-tools, just try your solution and you'll see it works.不要担心出现在开发工具中的通用名称,只需尝试您的解决方案,您就会发现它有效。

For something that shows up in dev-tools, you could use useDebugValue .对于开发工具中显示的内容,您可以使用useDebugValue

You haven't made a mistake.你没有犯错。 If you want to use separate hooks like this, this is how they will appear in React DevTools.如果你想像这样使用单独的钩子,这就是它们在 React DevTools 中的显示方式。 If you want to have name label associated with each hook, check out this StackOverflow answer:如果您想将名称 label 与每个挂钩关联,请查看此 StackOverflow 答案:

Is there any way to see names of 'fields' in React multiple state with React DevTools when using 'useState' hooks 使用“useState”钩子时,有什么方法可以使用 React DevTools 在 React 多个 state 中查看“字段”的名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM