繁体   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