ReactJs-如何更新数组中的状态
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);
}
相关文章:
- 从组件状态的数组中删除元素
- 如何在React中更改处于状态的数组
- ReactJS-这个状态中的数组在删除时被正确更新,但结果是't,直到以后的状态发生变化
- 从数组中删除元素,然后保留其状态以备将来使用,而不使用全局变量
- 如何使用Handlebars.js按状态拆分对象数组
- 如何从状态数组中删除项目
- React-Redux:当连接到处于状态的数组时无限循环
- 在 ReactJs 状态上将项目添加到数组中,并超时以进行自我删除
- 从 0 和 1 的数组恢复复选框的状态
- 如何推送到实际对象的数组最后状态,清除它并像新对象一样单独编辑
- 反应 redux 与给定数组的合并状态
- 将状态的数组长度设置为 0,但绑定列表仍剩下一个元素
- 在闭包中公开数组的状态,而不允许从外部对其进行编辑
- ReactJs-如何更新数组中的状态
- $_POST 变量保持活动状态多长时间,PHP 如何决定 post 数组中的内容
- Reactjs-对处于状态的对象数组进行排序
- 如何引用Angular Service返回的数组,以便维护状态
- 使用单例模式维护整个应用中的数组状态
- 清除Redux中的数组状态
- 如何在Node模块之间共享数组状态