http://jsbin.com/zehoceloka/1/edit推空數組反應的狀態
我輸入的數量是動態的,這取決於有多少數據具有API。所以首先我將它映射到視圖。但也有一個功能,用戶可以添加新項目。我試圖推新的空陣列,但沒有任何反應。我做錯了嗎?
class HelloWorldComponent extends React.Component {
constructor(){
super()
this.addNewRow = this.addNewRow.bind(this);
this.state = {
"rules":[
"age must be above 10",
"must wear shoe"
]
}
}
addNewRow(e){
const updated = this.state.rules.push("");
this.setState({rules:updated});
}
render() {
return (
<div>
{this.state.rules.map(obj =>
<input type="text" defaultValue={obj} />
)}
<button>Add New Rules</button>
<br /><br />
<pre>{JSON.stringify(this.state.rules,null,2)}</pre>
</div>
);
}
}
相關:http://stackoverflow.com/questions/30889465/better -faster-way-for-changing-react-array-state-than-cloning-it –