簡體   English   中英

在狀態對象中使用具有多個鍵/值對的React Hooks

[英]Using React Hooks with more than one Key/Value Pair in State Object

我不知道最好的方法是為Functional Componentstate定義多個key/value對。

在一類我會initialithe State

this.state = {
    first: 'foo',
    second: 'bar'
};

更新我打電話的State

this.setState({
    first: 'foobar'
    second: 'barfoo'
});

現在,使用React Hooks像這樣初始化State

const [first setfirst] = useState('foo');
const [second, setSecond] = useState('bar');

更新我打電話的State

setFirst = 'foobar';
setSecond = 'barfoo';

但是,恕我直言,這並不理想。 我必須重寫const [x, setX] = useState(...); 每當我想向State object添加新的key/value對時。 樣板。 我還必須始終記住x的“設置者”名稱setX 如果State object增加,那將變得混亂。

如果我能簡單地打電話給我會更好

setState(first: 'foobar', second: 'barfoo');

但是我不確定如何正確初始化State object /什么是最好的初始化方法。

使用對象作為初始值

您可以使用javascript object作為您的值。 這樣,您可以將更多變量放在一個對象中。 因此,您的代碼如下所示:

const [example, setExample] = useState({first:'foobar', second:barfoo''});

然后,您可以像這樣更新它:

setExample({...example,first:'new foobar'})
setExample({...example,second:'new foobar second'})

這種類型的setting會破壞您以前的值,並用舊值替換新值。

使用該對象,您只需要將新property添加到example的初始化以及需要設置它的位置。

作為一個復雜的示例,您可以訪問以下鏈接:

與對象反應掛鈎useState()


通知 (更新變量)

如果您僅使用{first:'new foobar'}更新它,並且不在屬性中包含second ,則可能會丟失第二個的舊值。 因此,使用...example保留舊值second

您可以使用useState設置整個對象,如下所示-

const [stateObj, setStateObj] = useState({first:'foobar', second:'barfoo'});

然后更新狀態-

setStateObj({first:'foobarnew', second:'barfoonew'})

您可以自己動手做這個!

function useMultipleStates() {
    const [first setFirst] = useState('foo');
    const [second, setSecond] = useState('bar');

    const setState = (f, s) => {
        setFirst(f);
        setSecond(s);
    }

    return {
        first,
        second,
        setState,
    }
}

您可以根據自己的需要進行調整,但是如果可以給您一個有關如何做的想法。

在React docs中 :當您具有涉及多個子值的復雜狀態邏輯時,或者當下一個狀態依賴於前一個時, useReducer通常比useState更可取。 useReducer還可以讓您優化觸發深層更新的組件的性能,因為您可以傳遞調度而不是回調。

const initialState = { first: '', second: '' };

function reducer(state, action) {
  switch (action.type) {
    case 'doFirst':
      return {...state, first: 'newFirst' };
    case 'doSecond':
      return {...state, second: 'newSecond' };
    default:
      throw new Error();
  }
}

function Component() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      {state.first}
      {state.second}
      <button onClick={() => dispatch({type: 'doFirst'})}></button>
      <button onClick={() => dispatch({type: 'doSecond'})}></button>
    </>
  );
}

我建議去使用減速鈎。 React官方網站說,如果您有復雜的狀態,請使用userReducer掛鈎。



const initialState = {
first: 'foo',
second: 'bar'
};

function reducer(state, action) {
  switch (action.type) {
    case 'updateFirst':
      return {...state, first: 'fooBar' };
    case 'updateSecond':
      return {...state, second: 'barfoo' };
    case 'updateBoth':
      return {...state, second: 'barfoo',first: 'fooBar' };
    default:
      throw new Error();
  }
}

function Component() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      {state.first}
      {state.second}
      <button onClick={() => dispatch({type: 'updateFirst'})}>UpdateFirst</button>
      <button onClick={() => dispatch({type: 'updateSecond'})}>UpdateSecond</button>
      <button onClick={() => dispatch({type: 'updateBoth'})}>UpdateBoth</button>
    </>
  );
}


代碼: https : //codesandbox.io/s/busy-rosalind-9oiow

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM