[英]ReactJs - How to update state in array?
我正在用React创建一个页面构建器。
我有一个包含页面结构的组件。
var LayoutPage = React.createClass({
getInitialState: function getInitialState() {
return {
items: {
'78919613':{
id: '78919613',
component : 'OneColumn',
cols:{
'565920458':{
id: '565920458',
content:{
'788062489':{
id: '788062489',
component : 'Text',
params: 'Lorem ipsum'
},
'640002213':{
id: '640002213',
component : 'Text',
params: 'Lorem ipsum'
}
}
}
}
}
}
};
},
.....
});
我有一个具有拖放功能的系统,可以在页面上放置一个新元素,并且可以正常工作。 但是当删除新元素时,我想更新状态以在数组中添加新项。
那么我该如何推新项目呢? 我做了一个测试:
this.state.items.push({.....});
但是我有一个错误:
TypeError: this.state.items.push is not a function
你能帮助我吗 ?
谢谢。
与其在您的状态下使用对象,不如将其更改为如下所示的数组:
this.state = {
items: [ // items array
{
id: 1,
name: "Stack"
},
{
id: 2,
name: "Overflow"
}],
count: 3, // another state
textValue : '' // and this is state too
}
其中的项目是一个对象数组。 然后,您将能够向阵列添加新项目。
const newItem = {
id : this.state.count,
name: this.state.textValue
};
const newArr = this.state.items.concat(newItem);
this.setState({
items: newArr,
textValue: '',
count: this.state.count + 1
})
整个例子在这里 。
希望对您有帮助!
谢谢
如果直接更改应用程序的状态,就会开始感到头痛。 如果您忘记调用this.setState
,它将不会重新渲染!
假设您不能使用数组(这会更容易),那么如果您想向对象添加另一个项目,则必须生成一个唯一键。
// create a new copy of items based on the current state
var newItems = Object.assign({}, this.state.items),
newItem = { id: '', component: '', cols: {} },
uniqueId = generateUniqueId();
// safely mutate the copy
newItems[uniqueId] = newItem;
// update the items property in state
this.setState({ items: newItems });
使用ES7 / Babel甚至更容易。
const newItem = { id: '', component: '', cols: {} },
uniqueId = generateUniqueId(),
items = { [uniqueId]: newItem, ...this.state.items };
this.setState({ items });
您可以使用Math.random
生成与您拥有的唯一ID相似的唯一ID。
function generateUniqueId() {
// removing leading '0.' from number
return Math.random()
.toString()
.slice(3);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.