简体   繁体   English

替换数组中的值后如何立即更新反应 state

[英]How to instantly update react state after replacing the value from array

I have a function which gets the user input and update the array if the same key is available already.我有一个 function,如果相同的键已经可用,它会获取用户输入并更新数组。 with the help of this article在这篇文章的帮助下

This is how it looks;这就是它的样子;

  const handleClickYes = (question) => {
    // find if question is in the data array
    const hasQuestion = data.find(({ parentId }) => question.id === parentId)
    
    const indexOfQuestion = data.indexOf(hasQuestion)
    
    if (hasQuestion) {
      // update the value with specific selected index in the array. 
      data[indexOfQuestion] = { question: question.if_yes, parentId: question.id, userChoice: 'YES', child: [] }
    } else {
      setData((data) => data.concat({ question: question.if_yes, parentId: question.id, userChoice: 'YES', child: [] }))
    }
    localStorage.setItem('deviceReport', JSON.stringify(data))
  }

I'm using localStorage to persist the state我正在使用 localStorage 来保存 state

  const deviceReport = localStorage.getItem('deviceReport') ? JSON.parse(localStorage.getItem('deviceReport')) : []
  const [data, setData] = useState(deviceReport)

Here the problem is if I use setData then it updates instantly but on replacing the array at this part这里的问题是如果我使用 setData 那么它会立即更新但是在这部分替换数组

data[indexOfQuestion] = { question: question.if_yes, parentId: question.id, userChoice: 'YES', child: [] }

it dosent update the mapped data on JSX portion.它不会更新 JSX 部分的映射数据。 How can I configure it to update it happen in setState.我如何配置它以更新它发生在 setState 中。 ? Or any other better option to update the array.或者更新数组的任何其他更好的选择。

You're not calling setState() within the first half of your if block.您没有在if块的前半部分调用setState() Also, never mutate state directly .另外,永远不要直接改变 state Make a mutable copy, like so:制作一个可变副本,如下所示:

const handleClickYes = (question) => {
  // find if question is in the data array
  const hasQuestion = data.find(({ parentId }) => question.id === parentId);

  const indexOfQuestion = data.indexOf(hasQuestion);

  // copy data to mutable object
  let newData = [...data];
  if (hasQuestion) {
    // update the value with specific selected index in the array.
    newData[indexOfQuestion] = {
      question: question.if_yes,
      parentId: question.id,
      userChoice: "YES",
      child: [],
    };
  } else {
    //   concat existing data with a new question
    newData = [
      ...newData,
      {
        question: question.if_yes,
        parentId: question.id,
        userChoice: "YES",
        child: [],
      },
    ];
  }
  localStorage.setItem("deviceReport", JSON.stringify(newData));
  setData(newData);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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