gpt4 book ai didi

javascript - 使用 concat 更新 react 状态下的数组

转载 作者:行者123 更新时间:2023-12-02 22:14:21 24 4
gpt4 key购买 nike

我有一个复选框组件,基本上我想做的是制作选中的数组并将信息发送到 api。但我无法更新状态数组而不删除最后插入的对象。我使用 concat 仍然得到相同的结果。这是整个组件的代码:

import React, { Fragment, Component } from 'react';
import { Inputt, Checkbox } from './style';

interface Istate {
checked: boolean;
products?: any[];
}
interface Iprops {
id: any;
value: any;
changeValue?: (checkBoxId: string, value: any) => void;
}
class CheckBoxComp extends Component<Iprops, Istate> {
state = {
checked: true,
products: [] as any,
};

addOne = (id: any, checked: any) => {
let { products } = this.state;
const newObj = { id, checked };
products = products.concat(newObj);
this.setState({ products }, () => {
console.log(products);
});
};

isChecked = (id: any) => {
const { checked, products } = this.state;
const { changeValue } = this.props;
this.setState({
checked: !checked,
});
if (changeValue) {
changeValue(id, checked);
}
this.addOne(id, checked);
};

render() {
const { id, value } = this.props;
const { checked, products } = this.state;
return (
<Fragment>
<Checkbox>
<span />{' '}
<label className="checkbox-wrapper">
<span className="display" />
<Inputt
type="checkbox"
value={checked}
onChange={() => {
this.isChecked(id);
}}
/>
<span className="checkmark" />
</label>
</Checkbox>
</Fragment>
);
}
}

export default CheckBoxComp;

最佳答案

您可以尝试这种利用展开运算符来制作数组副本的方法:

addOne = (id: any, checked: any) => {
this.setState((state: Istate): Partial<Istate> => ({
products: [
...state.products,
{ id, checked },
],
}), () => console.log(this.state.products));
};

关于javascript - 使用 concat 更新 react 状态下的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59443397/

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