简体   繁体   中英

React Props updating on set state hook

The props to the child component is updating on handleOnChange event. Below is sample code structure.

 const { useCallback, useEffect, useState } = React; //think this is coming from parent obj const retrieveData = () => Promise.resolve({ English: { v1: "10", v2: "11", v3: "34" }, Hindi: { v1: "14", v2: "16", v3: "18" }, }); const createKey = (...values) => values.join("-"); const splitKey = (key) => key.split("-"); const App = ({ retrieveData }) => { const [data, setData] = useState(retrieveData.English); //this retrieveData.English always updating on handleChange useEffect(() => { retrieveData().then(setData); }, []); const handleChange = useCallback(({ target }) => { const [lang, key] = splitKey(target.name); setData((oldData) => { const newData = {...oldData }; newData[lang][key] = target.value; return newData; }); }, []); return ( <form> {Object.entries(data).map(([lang, item]) => ( <div key={lang} className="row"> <div className="head">{lang}</div> <ul> {Object.entries(item).map(([key, val]) => ( <li key={createKey(lang, key)}> <label>{key}</label> <input name={createKey(lang, key)} value={val} onInput={handleChange} /> </li> ))} </ul> </div> ))} </form> ); }; ReactDOM.createRoot(document.getElementById("root")).render(<App />);
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

In the above case, the props obj value also updating on the handleChange setData . I am not sure what I am missing. I need to compare the initial obj values with handle change values. Any idea on this.

in this way, the state will be updated with the data entered in the input.

const [initVal, setInitVal] = useState(obj.values)
  const handleChange = (e) => {
    setInitVal(e)
  })
  <input value={initVal} onChange={(e) => handleChange(e.target.value)} />
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM