2017-01-20 80 views
0

我正在學習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,但我願意使用其他庫和工具來幫助我。

+0

你能分享你的渲染功能嗎?對我來說,它似乎是更好地理解你的最終目標的最後一塊難題。 –

+0

@connected_user添加了一些更多的代碼,對不起有點難,因爲我有很多子組件 – Bender

+0

您是否正在根據用戶看到的描述更新描述?用戶在何處查看說明? –

回答

0

我的答案不是關鍵值,但它非常有效。 您可以在渲染函數中傳遞項目的索引。 我也考慮過與ID的關鍵對象。但是你無法確定訂單是什麼時候循環。

var List = React.createClass({ 
    render: function(){ 
    return (
     <ul className="no-list no-pad items"> 
     { 
     this.props.items.map(function(item, index) { 
      return <ListItem key={item.id} item={item} index={index} update_description={this.props.update_description} /> 
     }, this) 
     } 
     </ul> 
    ) 
    } 
}); 

並將其傳遞給update_description,然後您可以使用索引來更新描述。

update_description: function(index, description) { 
    var items = this.state.items; 
    items[index].description = description; 
    this.setState({ items: state }); 
}, 
1

在算法層面上,您將維護一個無序的元素數組並對特定元素執行線性搜索。如您所述,這不是非常有效。你應該使用一個散列表來代替使用一個數組,而這個散列表將允許分期恆定時間查找。在JavaScript中,您可以使用一個對象,或者可以使用ES2015中引入的Map(),因此可能不支持所有瀏覽器。

通過使用id作爲對象/圖的關鍵字,在您的update_description()函數中,您可以直接訪問與該關鍵字關聯的元素。由於在這種情況下這些元素是對象,因此您可以修改該特定對象的description屬性。您仍然需要撥打this.setState({})才能讓React重新呈現。

有關使用setState()具有可變數據結構的更多信息,請參閱setState()