【问题标题】:combining useState hook in a react component在反应组件中结合 useState 钩子
【发布时间】:2020-08-03 03:47:27
【问题描述】:

我最近开始大量使用 react hooks。

使用“React.useState”时,状态管理对我来说似乎更直观。

无论如何,虽然它工作正常,但我知道我开始保存到 state 的值越多,它就会开始变得混乱。

例如,随着我的汽车零件应用程序的发展,它现在看起来像这样:

const [isShown, setIsShown] = React.useState(false);
const [idVal, setIdValue] = React.useState(false);
const [partNameVal, setPartNameValue] = React.useState(false);
const [engineEngineEngineTypeVal, setEngineEngineTypeValue] = React.useState(false);
const [displacementVal, setDisplacementValue] = React.useState(false);
const [makeVal, setMakeValue] = React.useState(false);
const [countryVal, setCountryValue] = React.useState(false);

const hide = () => setIsShown(false);

const show = (id, partName, engineEngineType, displacement, department, country) => {
    setIsShown(true);
    setIdValue(id);
    setPartNameValue(partName);
    setEngineTypeValue(engineEngineType);
    setDisplacementValue(displacement);
    setMakeValue(department);
    setCountryValue(country);
}

<p>ID:  {idVal}</p>
<p>PartName:  {partNameVal}</p>
<p>EngineType:  {engineEngineTypeVal}</p>
<p>Displacement:  {displacementVal}</p>
<p>Make:  {makeVal}</p>
<p>Country:  {countryVal}</p>

我想知道是否有办法让它更易读,但仍然非常直观。

谢谢!

【问题讨论】:

    标签: reactjs react-hooks react-state-management


    【解决方案1】:

    通常您想处理单个对象或使用useReducer,例如:

    const INITIAL_CAR = {
      id: 0,
      part: "4xE3",
      country: "USA",
      // ... More entries
    };
    
    const CarApp = () => {
      const [car, setCar] = useState(INITIAL_CAR);
      const [isShown, setIsShown] = useState(false);
    
      const show = (carProps) => {
        setIsShown(true);
        setCar(carProps);
      };
    
      const { id, part, engine, displacement, make, county } = car;
    
      const updateCountry = (country) =>
        setCar((prevCar) => ({ ...prevCar, country }));
    
      const updateCarProperty = ({ property, value }) =>
        setCar((prevCar) => ({ ...prevCar, [property]: value }));
    
      return (
        <div>
          {isShown && (
            <>
              <p>ID: {id}</p>
              <p>PartName: {part}</p>
              <p>EngineType: {engine}</p>
              <p>Displacement: {displacement}</p>
              <p>Make: {make}</p>
              <p>Country: {country}</p>{" "}
            </>
          )}
          // use show, updateCountry, updateProperty etc.
        </div>
      );
    };
    

    【讨论】:

    • 谢谢 你能举例处理状态的所有其他部分,如部件名称、引擎类型等吗?
    【解决方案2】:

    我会说useReducer hook 就是这种情况。

    https://reactjs.org/docs/hooks-reference.html#usereducer

    const initialState = {
          isShown: false,
          idVal: 0,
          ....
    };
    
    function reducer(state, action) {
      switch (action.type) {
        case 'show':
          return {
            ...state,
            isShown: true,
            idVal: action.payload.idVal
          };
        case 'hide':
          return {
            ...state,
            isShown: false
          }
        ...
        default:
          throw new Error();
      }
    }
    
    const [state, dispatch] = useReducer(reducer, initialState);
    
    dispatch({type: 'show', payload: { idVal: 1}})
    

    【讨论】:

      【解决方案3】:

      您可以创建一个新文件以从组件中提取所有挂钩逻辑。

      打电话给useHooks.js

      export default () => {
      const [isShown, setIsShown] = React.useState(false);
      const [idVal, setIdValue] = React.useState(false);
      const [partNameVal, setPartNameValue] = React.useState(false);
      const [engineEngineEngineTypeVal, setEngineEngineTypeValue] = React.useState(false);
      const [displacementVal, setDisplacementValue] = React.useState(false);
      const [makeVal, setMakeValue] = React.useState(false);
      const [countryVal, setCountryValue] = React.useState(false);
      
      const hide = () => setIsShown(false);
      
      const show = (id, partName, engineEngineType, displacement, department, country) => {
          setIsShown(true);
          setIdValue(id);
          setPartNameValue(partName);
          setEngineTypeValue(engineEngineType);
          setDisplacementValue(displacement);
          setMakeValue(department);
          setCountryValue(country);
      }
      
      return [isShown, idVal, partNameVal, engineEngineEngineTypeVal, displacementVal, 
      makeVal, countryVal, show, hide];
      }
      

      这里的想法是将所有钩子逻辑放在一个函数中,并在 JSX 中返回所需的值。

      并在您的组件中导入并使用从 useHooks 导出的所有属性

      import useHooks from './useHooks';
      
      const [isShown, idVal, partNameVal, engineEngineEngineTypeVal, displacementVal, 
      makeVal, countryVal, show, hide] = useHooks();
      

      希望思路清晰

      【讨论】:

        【解决方案4】:

        我主要处理组件中这么多状态的方式是使用一个useState,这样它只是一个大对象。

        这是一个小例子:

        const [state, setState] = useState({
          num: 1,
          cars: ['volvo', 'mazda'],
          john: {name: 'John', last: 'Foo'}
        })
        

        如果你想改变我通常使用这个功能的东西

        const onChange = (name, value) => {
          setState(prevState => ({...prevState, [name]: value}))
        }
        

        这会将键 name 更改为值 value。这在我眼里更加清晰。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-03-21
          • 2020-09-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-03
          相关资源
          最近更新 更多