簡體   English   中英

更新反應鈎子中的嵌套 object

[英]Updating nested object in react hooks

我目前正在嘗試實現一個動態+多步表單,並且想知道如何在 map 中更新 map 的值。

例如:我有三個字段“名字”、“姓氏”、“電子郵件”。 我想將名稱值存儲在一個名為“General”的鍵中,而 email 值我想存儲在一個名為“Contact”的鍵中。 目前,我已經實現了一個名為onChange的方法,該方法賦予每個字段並監聽更改並將字段及其值存儲在 state 中。

function App() {
  const [state, setState] = useState(false);

  const onChange = (field, value) => {
    console.log("Values:", value);

    setState({
      ...state,
      [field]: value
    });

    console.log("State:", state);
  };

  return (
    <div className="App">
      <EuiForm>
        <EuiFormRow label="First Name">
          <EuiFieldText
            name="first"
            onChange={event => onChange("firstName", event.target.value)}
          />
        </EuiFormRow>
        <EuiSpacer />

        <EuiFormRow label="Last Name">
          <EuiFieldText
            name="last"
            onChange={event => onChange("lastName", event.target.value)}
          />
        </EuiFormRow>
        <EuiSpacer />

        <EuiFormRow label="Email">
          <EuiFieldText
            name="email"
            onChange={event => onChange("email", event.target.value)}
          />
        </EuiFormRow>
        <EuiSpacer />

        <EuiButton type="submit" fill>
          Save form
        </EuiButton>
      </EuiForm>
    </div>
  );
}

更新值的正確方法是什么,以便我的 state 中的數據看起來像這樣?

{
  "general": {
    "firstName": "ABCD",
    "lastName": "EFGH"
  },
  "contact": {
    "email": "abcd@efgh.com"
  }
}

最初將 state 作為object ,像這樣

const [state, setState] = useState({ general :{}, contact:{});

比做這樣的事情

const onChange = (field, value) => {
    var temp = {...state}
   if(field == 'firstName'){
      temp.general.firstName = value
      setState({
      ...state,
      general:temp
    });
   } else if(field == 'lastName'){
      temp.general.lastName= value
      setState({
      ...state,
      general:temp
    });
   } else if(field == 'email'){
      temp.contact.email= value
      setState({
      ...state,
      contact:temp
    });
   }

    console.log("State:", state);// this will not work as the setState is asynchronous


};


  // so you can view the state like this 
 useEffect(() => {
     console.log('State', state);  // so this block of code will watch for any changes in state
  }, [state]);

為簡化起見,您可以定義兩個不同的狀態,然后在提交時將它們合並。 這是一個例子:

 function App() { const [general, setGeneral] = React.useState({}); const [contact, setContact] = React.useState({}); const onChange = (set, field, value) => { set(state => ({...state, [field]: value })); }; const onSubmit = (e) => { e.preventDefault(); console.log({ general, contact }); } return ( <div className="App"> <form onSubmit={onSubmit}> <label htmlFor="First Name">First Name <input name="first" onChange={event => onChange(setGeneral, "firstName", event.target.value)} /> </label> <hr /> <label htmlFor="Last Name">Last Name <input name="last" onChange={event => onChange(setGeneral, "lastName", event.target.value)} /> </label> <hr /> <label htmlFor="Email">Email <input name="email" onChange={event => onChange(setContact, "email", event.target.value)} /> </label> <hr /> <button type="submit"> Save form </button> </form> </div> ); } ReactDOM.render(<App />, document.getElementById('root'));
 <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root"></div>

暫無
暫無

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

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