我有一个对象数组addon_categories
包含一个属性id
和另一个数组:addons
。当用户切换复选框时,状态应该相应更新:其中包括添加或删除所选类别下的“addons”数组。如何通过更新对象数组中特定对象内的数组来更新状态?
this.state = { addon_categories: [] };
// example of filled state
this.state = { addon_categories: [
{ id: 3, addons: [ 1 ] },
{ id: 2, addons: [ 1, 4, 11 ] },
{ id: 4, addons: [ 3, 4] }
] };
这是更的JavaScript
多于React
的问题的不同之处在于数据必须被最终更新为成分的状态。作为JavaScript的初学者,我无法用包含一些属性和数组的对象数组来更新状态对象。在下面的代码中,为特定类别更新addons
数组(适用于删除和推送)的正确逻辑是什么?
这里的逻辑:
如果类别ID不存在,简单地增加一个新的对象与该类别ID和附加元件阵列与单个附加ID。 [✓]
如果类别ID存在,
- >检查addon_id是否存在于此类别中。
- >如果addon_id存在于此类别中,请从此对象中的addons数组中删除addon id [?]
- >如果addon_id不存在,请将此addon id插入此对象中的addons数组[
这是我的代码。
import React from 'react';
import { connect } from 'react-redux';
import store from '../../../../reducers/store';
import fetchFood from '../../../../actions/restaurant/food_get';
class AddonsModal extends React.Component
{
constructor(props)
{
super(props);
this.state = { addon_categories: [] };
this.onAddonChange = this.onAddonChange.bind(this);
}
/*
* Handle click, toggle addon change
*/
onAddonChange(e)
{
const c = +e.target.name; // category_id from input
const a = +e.target.id; // addon_id from input
// create new instance of this.state.addon_categories
let addon_categories = this.state.addon_categories.slice();
if (!this.addonCategoryExists(c))
{
// CATEGORY DOESNT EXIST, SO NEW CATEGORY AND ADDON ADDED!
addon_categories.push({ id: c, addons: [a] });
this.setState({ addon_categories },() => console.log('NEW STATE', this.state.addon_categories));
}
else
{
// CATEGORY EXISTS
if (this.addonExistsInCategory(c, a))
{
// ?? ADDON EXISTS IN THIS CATEGORY, SO NEED TO REMOVE IT
}
else
{
// ?? ADDON DOESNT EXIST IN CATEGORY SO NEED TO ADD IT TO JUST THIS CATEGORY
}
}
}
addonCategoryExists(c)
{
return !! this.state.addon_categories.filter(category => category.id === c).length;
}
addonExistsInCategory(c, a)
{
let verified = false;
let categories = this.state.addon_categories.filter(category => category.id === c);
categories.forEach(category =>
{
if (category.addons.includes(a)) { verified = true; }
});
return verified;
}
componentDidMount()
{
store.dispatch(fetchFood(this.props.Restaurant.id, this.props.food.id));
}
render()
{
let food = this.props.food;
let foodData = this.props.foodDetails.food.data;
let addon_categories = foodData ? foodData.data.addon_category : null;
return (
<div className="row">
{addon_categories && addon_categories.map(category => { return (
<div className="col-xs-12" key={category.id}>
<div className="pop-up-dish-specials">
<h2>{category.name}</h2>
{category.addons && category.addons.map(addon => { return (
<div key={addon.id}>
{/* for simplicity, i've sent the category_id in name and addon_id in id property */}
<input type="checkbox" name={category.id} id={addon.id} onChange={this.onAddonChange}/>
<label htmlFor={addon.id}>{addon.name}</label>
</div>
)})}
</div>
</div>
)})}
</div>
)
}
}
function mapStateToProps(state)
{
return { foodDetails: state.foodDetails }
}
export default connect(mapStateToProps)(AddonsModal);
这是很好的解决方案,非常感谢。 – anonym
我想进一步分解两个删除条件。 '[#1]'删除整个'addon_category对象',如果它是其中唯一的插件,'[#2。]'如果有多个(完成✓),就从阵列中删除插件。我无法使用'if(category.id === c && category.addons.length === 1){return addon_categories.splice(index,1); }' – anonym
您的解决方案将无法正常工作,因为拼接会返回已删除的项目,因此它不会对您有所帮助。你可以做2件事 - 或者只是修改我的代码返回到这样的'newAddons.length? {id:category.id,addons:newAddons}:undefined',然后在设置状态时,您将执行addon_categories:newCategories.filter(category => category)'(这样您可以从数组中过滤一个未定义的值。这样做是为了保存类别索引值,然后在设置状态之前使用splice从newCategories中删除它。 –