我似乎有问题将数据推入一个状态数组。 我正试图以这种方式实现它:
this.setState({ myArray: this.state.myArray.push('new value') })
但我相信这是不正确的方式,并导致问题的可变性?
我似乎有问题将数据推入一个状态数组。 我正试图以这种方式实现它:
this.setState({ myArray: this.state.myArray.push('new value') })
但我相信这是不正确的方式,并导致问题的可变性?
当前回答
使用react钩子,你可以这样做
const [countryList, setCountries] = useState([]);
setCountries((countryList) => [
...countryList,
"India",
]);
其他回答
React-Native
如果你也想要你的用户界面(例如。ur flatList)是最新的,使用PrevState: 在下面的例子中,如果用户点击按钮,它将添加一个新对象到列表中(包括在模型和UI中)。
data: ['shopping','reading'] // declared in constructor
onPress={() => {this.setState((prevState, props) => {
return {data: [new obj].concat(prevState.data) };
})}}.
我想现在回答这个问题有点晚了,但对于那些新来的人来说
你可以使用这个叫做immer的小包
请看这个例子:https://immerjs.github.io/immer/produce
使用es6可以这样做:
this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array
传播的语法
使用react钩子,你可以这样做
const [countryList, setCountries] = useState([]);
setCountries((countryList) => [
...countryList,
"India",
]);
你破坏了React的原则,你应该克隆旧的状态,然后将其与新数据合并,你不应该直接操纵你的状态, 你的代码应该是这样的
fetch (http://localhost: 8080”)。然后(response => response.json)。然后(json ={这个setState ({mystate ...这个state university)。我的状态,杰森]