我正在學習React的過程中,但是我不完全明白的是當您擁有大型數據結構時更新狀態的最佳方法。下面是一個簡單的例子我在做什麼,所以在我父組件我設置像這樣React - 如何通過鍵值更新狀態
getInitialState: function(){
return {
initialItems: [
{"id": 1, "name": "Apples", "description": "Description"},
{"id": 2, "name": "Broccoli", "description": "Description"},
{"id": 3, "name": "Chicken", "description": "Description"},
{"id": 4, "name": "Duck", "description": "Description"}
],
items: []
}
},
然後我有一個函數在該組件的狀態更新,我傳遞到子組件的說明使用道具
update_description: function(id, description) {
var state = this.state.items.map(function(item) {
return {
id: item.id,
name: item.name,
description: (item.id === id ? description: item.description),
};
}, this);
this.setState({ items: state });
},
然後在我的渲染功能
render: function() {
return (
<List items={this.state.items} update_description={this.update_description} />
);
}
我的子組件
var List = React.createClass({
render: function(){
return (
<ul className="no-list no-pad items">
{
this.props.items.map(function(item) {
return <ListItem key={item.id} item={item} update_description={this.props.update_description} />
}, this)
}
</ul>
)
}
});
這可行,但它看起來效率很低(特別是如果你有一個大的數據結構),因爲代碼循環所有的項目,並檢查ID是否匹配,如果它確實更新描述。此外,如果我爲每個項目添加另一個屬性(如「圖像」),則需要記住更新update_description
函數。
理想情況下,我想要一種即將說「更新描述屬性,其中ID等於我傳遞給函數的描述屬性」的方式。有點像你在SQL中做的。
這可能嗎?目前我只使用React,但我願意使用其他庫和工具來幫助我。
你能分享你的渲染功能嗎?對我來說,它似乎是更好地理解你的最終目標的最後一塊難題。 –
@connected_user添加了一些更多的代碼,對不起有點難,因爲我有很多子組件 – Bender
您是否正在根據用戶看到的描述更新描述?用戶在何處查看說明? –