本文介绍了反应:更新嵌套状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用本机反应.假设我有这个状态:

I'm using react native. Suppose I've this state:

{
persons: [{
  name: "Person",
  id: 0,
  value: "",
  percent: 50,
  messed: false
},
{
  name: "Person",
  id: 1,
  value: "",
  percent: 50,
  messed: false
}]
}

我想更新 id 1 的百分比.我如何使用 this.setState 来更新?我可以每次都深度克隆人对象并更新它,但我需要做很多次,而且人对象无论如何都非常大,所以它的性能效率不高.

I want to update, say, percent of id 1. How do I do it with this.setState? I can deep clone persons object every time and update it but I need to do it a lot of times and the persons object is quite large anyway so it's not performance-wise efficient.

目前我在做

this.state.persons[id].percent = 0;
this.forceUpdate();

这似乎不是那么反应-ish.我该怎么办?

which seems not so react-ish. How do I go about this?

推荐答案

您必须更新整个状态,这与您正在执行的操作非常相似.但是,我建议不要使用 this.forceUpdate(),而是建议调用 this.setState({person: this.state.persons }).

You would have to update the whole state, pretty similar to what you're doing. However, instead of using this.forceUpdate(), I'd recommend calling this.setState({ persons: this.state.persons }).

您可能想要做的是考虑将您的人员纳入该州.你可以做一些事情,比如根据他们的索引为每个人创建一个唯一的键.所以,索引是这样的:

What you may want to do is consider flatting out your persons into the state. You could do something like create a unique key for each based on their index. So, index of something like this:

const persons = getPersonsData();
this.setState({ persons });

改为这样做:

const persons = getPersonsData();
this.setState(persons.reduce((result, person, index) => Object.assign(result, { [`person${index}`]: person }));

persons.reduce 位将获取您的数组并创建一个像这样的对象:

The persons.reduce bit will take your array and create an object like this:

{
    person0: {},
    person1: {},
    person2: {}
}

然后,每个人都将处于平坦状态,因此您可以更直接地更新它.差别不大,但取决于您的用例,可能是值得的.

Then, each person will be flat in the state so you can just update it more directly. Not a huge difference, but depending on your use-case, could be worthwhile.

这篇关于反应:更新嵌套状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:26