Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
49 views
in Technique[技术] by (71.8m points)

javascript - setState hook changing another state

I'm new to React. I'm having the next problem...

At my functional component I have many states, there are 2 that have the sames fields (one is for an auxiliary operation)

const [fieldsToEdit, setFieldsToEdit] = useState({}); // This one get populated after the first render
const [auxFields, setAuxFields] = useState({.....})

Now, I have a button that calls a function, this functions just edits the 'fieldsToEdit', but it is editing the auxFields too! I realized this writing console.logs after and before of the setState call.

const updateEditHandler = (event) => {
  event.persist());


     setFieldsToEdit((prevState) => {
           const { name, value } = event.target;
           if(name === "fecha_presentacion")
              prevState[name] = value;
           else
              prevState[name] = Number(value);
           return ({
              ...prevState
         });
}

Am I doing it wrong? Hope you can help me.

question from:https://stackoverflow.com/questions/65831278/setstate-hook-changing-another-state

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should not mutate state. Instead create a new object without modifying the previous one.

prevState[name] = value; 
return { ...prevState };

The above first mutates the previous state, then returns a copy of it. Instead return a copy that contains the new value without modifying the previous state.

return { ...prevState, [name]: value };

The above copies the previous state and adds or overrides the (evaluated) name property with value. This is all done without mutating prevState.

Applying this to your actual code you would get the following.

setFieldsToEdit((prevState) => {
  const { name, value } = event.target;
  
  if (name == "fecha_presentacion") {
    return { ...prevState, [name]: Number(value) };
  } else {
    return { ...prevState, [name]: value };
  }
});

// or (depending on preference)
setFieldsToEdit((prevState) => {
  let { name, value } = event.target;
  if (name == "fecha_presentacion") value = Number(value);
  return { ...prevState, [name]: value };
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...