更新react本机安全中的数组



我是本地react的新手,我想更新对象数组中的数据!这是阵列:

const questions = [
{
question: "What kind of fruit was used to name a computer in 1945?",
answers: [
{ id: "0", text: "192.168.1.1", correct: false, userInput: false },
{ id: "1", text: "127.0.0.1", correct: true, userInput: false },
{ id: "2", text: "209.85.231.104", correct: false, userInput: false },
{ id: "3", text: "66.220.149.25", correct: false, userInput: false },
],
},
{
question: "What kind of fruit was used to name a computer in 1984?",
answers: [
{ id: "0", text: "Blackberry1", correct: false, userInput: false },
{ id: "1", text: "Blueberry", correct: false, userInput: false },
{ id: "2", text: "Pear", correct: false, userInput: false },
{ id: "3", text: "Apple", correct: true, userInput: false },
],
},
];

它是随机文本。我想更新第一个答案对象的userInput(当我按下按钮时(值,比如-

questions[0].answers[0].userInput = true;

当然,如果没有钩子,这是不起作用的,所以我用更改常量问题

const [questions, setQuestions] = useState([here i paste object array above])

我写了以下代码来检查按下按钮时值是否发生了变化。因此按钮onPress事件中的代码为:

questions[0].answers[0].userInput = true;
setQuestions([questions]);
console.log(questions); // to check outeput

当然什么也没发生,这个对象(questions[0].answers[0].userInput = true;)未更改那么我该怎么解决呢?我认为我应该创建数组的副本,然后更改这个值。我看到了这个可以帮助我的自由,但我不知道如何开始?

每当您试图在赋值操作的左侧部分使用状态值时,很有可能出现问题。但是,您也不需要复制整个结构。从本质上讲,你需要做一些React随意使用DOM做的事情——只为应该更新的部分提供新的值——但这次要用你的数据。

这里有一种可能的方法(假设您想更改问题q的答案a的值,将其userInput更改为true(:

const newQuestions = questions.map((question, i) => {
if (i !== q) return question; // non-affected questions will have the same ref
const newAnswers = question.answers.map((answer, j) => {
if (j !== a) return answer;
return {
...answer,
userInput: true
}
});
return { 
...question, 
answers: newAnswers
}
});
setQuestions(newQuestions);

在这种情况下,更新后您的状态中有三个引用更改:

  • 将新的数组引用传递给setState
  • 在这个数组中,只有更新的元素是具有更新答案的元素;再次,它的answers属性中存储了一个新的数组引用
  • 这个新数组主要由相同的元素组成;只有更改了userInput道具的才被实际替换

诚然,这里有很多代码,很容易丢失。值得庆幸的是,有很多工具可以简化这些数据操作。例如,这就是使用Immer编写相同代码的方式:

const nextQuestions = produce(questions, draftQuestions => {
draftQuestions[0].answers[0].userInput = true;
});
setQuestions(nextQuestions); 

什么?是的,就是这样。这是Immer文档页面上的一句名言:

使用Immer就像有一个私人助理。助理拿了一个信件(当前状态(,并给你一份复印件(草稿(以便记下更改向一旦你完成了,助理会拿着你的草稿为您生成真正的不可变的最后一个字母(下一个状态(。

最新更新