gpt4 book ai didi

dictionary - React JS setState({dict : dict })

转载 作者:行者123 更新时间:2023-12-03 14:15:24 28 4
gpt4 key购买 nike

我想知道这是否是用两个字典更新状态的正确解决方案

var PopulationCityView = React.createClass({
getInitialState: function() {
return {
prod_diff : {'wheat':0,'meat':0,'fish':0,'bread':0,'fruit':0,'wine':0,'beer':0,'wool':0,'cloth':0,'leather':0,'paper':0,'ceramics':0,'furniture':0,'glass':0}
};
},
componentWillMount: function() {
this.prod_diff = {'wheat':0,'meat':0,'fish':0,'bread':0,'fruit':0,'wine':0,'beer':0,'wool':0,'cloth':0,'leather':0,'paper':0,'ceramics':0,'furniture':0,'glass':0};
},
handleM: function(res,child_new_res_diff){
var new_prod_diff = this.prod_diff;
new_prod_diff[res] = child_new_res_diff;
this.setState({prod_diff:new_prod_diff});
},
render: function(){
........

如果有人知道更好更快的解决方案会要求提示......

最佳答案

更安全、更有效的方法是将状态保持为具有原始值的简单对象:

var PopulationCityView = React.createClass({
getInitialState: function() {
return {
wheat: 0,
meat: 0,
fish: 0,
};
},
handleM: function(res,child_new_res_diff){
var new_state = {};
new_state[res] = child_new_res_diff;
this.setState(new_state);
},
render: function() { /* your render code */ }
});

如果您确实必须将值存储在嵌套对象中,则必须记住在修改嵌套对象之前克隆它:

var PopulationCityView = React.createClass({
getInitialState: function() {
return {
prod_diff: { wheat: 0, meat: 0, fish: 0 }
};
},
handleM: function(res,child_new_res_diff){
var new_prod_diff = _.clone(this.state.prod_diff);
new_prod_diff[res] = child_new_res_diff;
this.setState({ prod_diff: new_prod_diff });
},
render: function() { /* your render code */ }
});

为了简化代码示例,我将您的初始状态缩小了一点。

还可以考虑使用React Immutability Helpers这使得对状态内的嵌套对象进行操作更加安全。

关于dictionary - React JS setState({dict : dict }),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27780104/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com