我有一个类(Cookbook)将单击处理程序“handleOnChange”传递给子组件(Filter)。过滤器呈现复选框。在那些复选框上,我执行handleOnChange。我想更新Cookbook中存在的状态,但即使在Cookbook中声明了handleOnChange,它也无法识别this.state.selectedStaples。该错误发生在第一个非console.log行的handleOnChange函数中。如何在Cookbook中更新selectedStaples的状态?
这是Cookbook
class Cookbook extends React.Component {
constructor(){
super();
this.state ={
cookbook: data,
selectedStaples: [],
}
}
getStapleList(recipes){
let stapleList = [];
recipes.forEach(function(recipe){
recipe.ingredient_list.forEach(function(list){
stapleList.push(list.needed_staple);
});
});
let flattenedStapleList = stapleList.reduce(function(a,b){
return a.concat(b);
})
return flattenedStapleList
}
handleOnChange(staple, isChecked, selectedStaples) {
console.log(staple);
console.log(isChecked);
console.log(selectedStaples);
const selectedStaples = this.state.selectedStaples;
// if (isChecked) {
// this.setState({
// selectedStaples: selectedStaples.push(staple)
// })
// } else {
// this.setState({
// selectedStaples: selectedStaples.filter(selectedStaple => selectedStaple !== staple)
// })
// }
}
render(){
const selectedStaples = this.state.selectedState;
const cookbook = this.state.cookbook;
const stapleList = this.getStapleList(cookbook.recipes);
return(
<div className="cookbook">
<div className="filter-section">
<h1>This is the filter section</h1>
<Filter stapleList = {stapleList} onChange={this.handleOnChange}/>
</div>
<div className="recipes">
<h1>This is where the recipes go</h1>
<div className="recipe">
<Recipe cookbook = {cookbook}/>
</div>
</div>
</div>
);
}
}
和过滤器
class Filter extends React.Component {
render(){
const stapleList = this.props.stapleList;
const checkboxItems = stapleList.map((staple, index) =>
<div key = {index}>
<label>
<input
type="checkbox"
value="{staple}"
onClick={e => this.props.onChange(staple, e.target.checked)}
/>
{staple}
</label>
</div>
);
return (
<form>
{checkboxItems}
</form>
);
}
}