在React Hooks中有设置状态的通用方法吗?如何管理多个状态? [英] Is there a generic way to set state in React Hooks? How to manage multiple states?

查看:61
本文介绍了在React Hooks中有设置状态的通用方法吗?如何管理多个状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,是否可以在React Hooks中使用 useState 泛型,就像我可以在React Components中同时管理多个状态一样?

I have a question, if I can use useState generic in React Hooks, just like I can do this in React Components while managing multiple states?

state = {
  input1: "",
  input2: "",
  input3: ""
  // .. more states
};

handleChange = (event) => {
  const { name, value } = event.target;
  this.setState({
    [name]: value,
  });
};

推荐答案

是的,使用钩子,您可以通过三种方式管理复杂的状态(没有第三方库),其中主要的原因是管理状态ID >及其对应的元素.

Yes, with hooks you can manage complex state (without 3rd party library) in three ways, where the main reasoning is managing state ids and their corresponding elements.

  1. 管理具有多个状态的单个对象(请注意,数组是一个对象).
  2. 如果( 1 )太复杂,请使用 useReducer .
  3. 为每个键值对使用多个 useState (考虑其可读性和维护性).
  1. Manage a single object with multiple states (notice that an array is an object).
  2. Use useReducer if (1) is too complex.
  3. Use multiple useState for every key-value pair (consider the readability and maintenance of it).

看看这个:

// Ids-values pairs.
const complexStateInitial = {
  input1: "",
  input2: "",
  input3: ""
  // .. more states
};

function reducer(state, action) {
  return { ...state, [action.type]: action.value };
}

export default function App() {
  const [fromUseState, setState] = useState(complexStateInitial);

  // handle generic state from useState
  const onChangeUseState = (e) => {
    const { name, value } = e.target;
    setState((prevState) => ({ ...prevState, [name]: value }));
  };

  const [fromReducer, dispatch] = useReducer(reducer, complexStateInitial);

  // handle generic state from useReducer
  const onChangeUseReducer = (e) => {
    const { name, value } = e.target;
    dispatch({ type: name, value });
  };
 
  return (
    <>
      <h3>useState</h3>
      <div>
        {Object.entries(fromUseState).map(([key, value]) => (
          <input
            key={key}
            name={key}
            value={value}
            onChange={onChangeUseState}
          />
        ))}
        <pre>{JSON.stringify(fromUseState, null, 2)}</pre>
      </div>

      <h3>useReducer</h3>
      <div>
        {Object.entries(fromReducer).map(([key, value]) => (
          <input
            name={key}
            key={key}
            value={value}
            onChange={onChangeUseReducer}
          />
        ))}
        <pre>{JSON.stringify(fromReducer, null, 2)}</pre>
      </div>
    </>
  );
}

注释

  • 与类组件中的 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};
});

请参考反应文档.

这篇关于在React Hooks中有设置状态的通用方法吗?如何管理多个状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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