我正在使用reactJS开发一个电子通讯站点,该站点的侧边栏中有复选框,并且编写了逻辑,但它正在选择所有复选框并过滤产品并显示过滤后的数据,但是当我取消选中时,它不会显示先前的状态。请帮助解决该问题。
class DashView extends Component {
constructor(props) {
super(props);
this.state = {
products: [],
isChecked: false
};
this.getProductList = this.getProductList.bind(this);
// this.clearCheck = this.clearCheck.bind(this);
}
componentDidMount() {
// const { isChecked } = this.state;
let apiUrl = ` https://api.myjson.com/bins/4xc0c`;
axios.get(apiUrl).then(res => {
// console.log(res.data.products);
this.setState({
products: res.data.products,
isChecked : this.state.isChecked
});
});
}
getProductList = item => {
const { products, isChecked } = this.state;
const prevProducts = this.state.products;
console.log(products);
// console.log(item);
let newProduct = [];
if ((isChecked === false && item === "smartphone") || item === "iphone") {
for (let i = 0; i < products.length; i++) {
if (products[i].ptype === item) {
console.log(item);
newProduct.push(products[i]);
}
}
console.log(newProduct);
this.setState({
products: newProduct,
isChecked: !isChecked
});
} else {
console.log("unchecked");
console.log(prevProducts);
this.setState({
prevProducts : this.state.products,
isChecked : !isChecked
})
}
}
答案 0 :(得分:0)
const prevProducts = this.state.products; //不正确
this.state.products
包含实际呈现的数据,已被过滤一次覆盖
console.log(newProduct); // filtered this.setState({ products: newProduct, // for rendering isChecked: !isChecked }); } else { console.log("unchecked"); this.setState({ prevProducts : this.state.products, // doesn't make sense here isChecked : !isChecked }) }
应该是:
console.log(newProduct); // filtered
this.setState({
prevProducts : this.state.products, // backup
products: newProduct, // for rendering
isChecked: !isChecked
});
} else {
console.log("unchecked");
console.log(prevProducts);
this.setState({
products : this.state.prevProducts, // restore, not filtered
isChecked : !isChecked
})
}
您还可以仅在加载时备份数据:
this.setState({
products: res.data.products, // for rendering
prevProducts: res.data.products, // for restoring from filtering
isChecked : this.state.isChecked
});