我目前正在尝试将 React 组件添加到多维数组的第三层中。我的结构如下:
constructor(props) {
super(props);
/**
* The state variables pertaining to the component.
* @type {Object}
*/
this.state = {
structure : [ // Block
[ // Slot 1
[ // Layer 1
<Text>text 1</Text>, // Text1
]
]
],
};
}
this.state.structure
包含 slots
的数组,其中包含 layers
的数组其中包含一个由 Text
组成的数组组件。
我尝试同时使用 concat()
和push()
尝试设置 structure
数组,但两者都给我错误,如“无法读取未定义的属性”等。这是我当前的 addText()
功能:
addText() {
this.setState((previousState) => ({
structure : previousState.structure[0][0].concat(<Text>text2</Text>),
}));
}
addText()
在我的应用程序中按下按钮时调用函数。
我还渲染了我的 Text
数组直接通过数组来获取当前层的组件:
{ this.state.structure[0][0] }
我觉得我正直面问题,但不知道是什么导致了问题。我希望能够添加另一个 Text
到容器,但我尝试做的任何事情似乎都不起作用。
最佳答案
一方面,您确实不应该将 React 组件的实例直接存储在 state
中。 。这样做只是自找麻烦,如渲染、状态更新、key
管理和数据持久性变得越来越难以争论。
相反,请将组件的模型存储在 state
中,一般都是他们应该有的 Prop 的形式。然后,在渲染时将这些模型转换为 React 组件:
this.state = {
structure : [ // Block
[ // Slot 1
[ // Layer 1
"text 1", // Text1
]
]
],
};
render() {
return this.state.structure[0][0].map(ea => <Text key={ea}>{ea}</Text>);
}
这样做更好,因为:如果您想读取或修改“层”数组的内容,会发生什么?如果它们是文本值,您可以简单地读取/修改文本。但如果它们是实例化的 React 组件……基本上没有办法在不跳过大量麻烦的情况下有效地更新你的状态。
关于您的具体问题:问题是当您评估这样的陈述时:
previousState.structure[0][0].concat(<Text>text2</Text>)
concat()
函数实际上返回连接后数组的值。现在该数组的值是(在本例中)[<Text>text 1</Text>, <Text>text2</Text>]
。所以,您实际上是在更新 state.structure
的值字段到一个完全不同的数组。我猜您看到的错误 - “无法读取未定义的属性” - 是因为当您尝试访问 this.state.structure[0][0]
时您试图像访问二维数组一样访问它,但它现在实际上是一维数组。
正如另一位回复者所说的更简洁:您将完全替换 state.structure
内容为state.structure[0][0]
(连接后)。
在 React 状态下更新深度嵌套的数据结构非常棘手。您基本上想要复制所有原始数据结构并仅更改其中的一部分。幸运的是,with ES6 "spread" operator我们有一个用于创建包含所有相同项目以及新项目的新数组的简写:
addText() {
this.setState((previousState) => {
// Copy the old structure array
const newStructure = [...previousState.structure];
// Update the desired nested array by copying it, plus a new item
newStructure[0][0] = [...newStructure[0][0], "text2"];
this.setState({structure: newStructure});
});
}
主要要点:
- 不要将 React 组件存储在状态中!存储原始数据并在渲染时使用它。
- 请小心更新内容
state
to - 它需要是相同的状态加上一些更新,而不是某些原子操作的结果。 - 阅读一些有关数组操作的知识,如
concat()
和push()
实际工作以及它们的返回值是什么。
关于javascript - 如何使用 setState() 修改 React Native 中的多维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57844119/