gpt4 book ai didi

javascript - 接收到的没有 true 和 false 属性的 api 响应数组,用于在 React 中动态创建复选框

转载 作者:行者123 更新时间:2023-12-02 23:40:38 24 4
gpt4 key购买 nike

我从 React-Redux Web 应用程序中的 api 结果创建了动态复选框,但问题是复选框结果不会在 onClick 上更新,从而设置新状态。应该能够使用 setState 函数更新状态。

我尝试使用下面这个链接中的解决方案,但它对我不起作用,因为我从 api 接收的有效负载不包含检查的属性或 true/false 属性。

Make an API call to dynamically create checkboxes in react

我收到的有效负载如下:

flavors: Array(3)
0: {id: "1001", name: "Spicy"}
1: {id: "1002", name: "Hot"}
2: {id: "1003", name: "Mediterranean"}

应该填充:

getInitialState = () => {

const initialState = {
customer: {
id: '',
firstName: '',
lastName: '',
email: ''
},
flavours: [] //Array to be populated, what is desired: {Spicy: false,
// Hot: false, Mediterranean: false}
// is populated currently as : Spicy, Hot,
// Mediterranean
},
return initialState;
}

从 api 和复选框处理程序方法获取有效负载:

 getAllFlavours() {
const { dispatch } = this.props;
dispatch(userActions.getFlavours()).then((response) => {
var flavourList = [];
for (var i = 0; i < response.flavours.length; i++) {
flavourList.push(response.flavours[i].name);
}
this.setState({
flavours: flavourList,
});
});
}

handleCheckboxChange(event) {
const target = event.target;
const isChecked = target.checked;
const name = target.name;
this.setState({ flavours: { ...this.state.flavours, [name]:
isChecked } });
}

创建复选框方法:

render() {

let flavourCheckboxes = this.state.flavours.map((item, i) => {
return (<FormGroup key={i}>
<Col>
<Label key={i}>{item}</Label>
</Col>
<Col>
<Input key={i} name={item} type="checkbox" checked={item} onClick=
{this.handleCheckboxChange} />
</Col>
</FormGroup>)
});

return (
// other html tags
<CardBody>
<Row>
{flavourCheckboxes} // checkboxes created
</Row>
</CardBody>
// other html tags

我希望该复选框能够选中和取消选中,并在 onclick 触发时更新状态,但目前我选中了所有值,您无法取消选中它们

NB: Also tried using defaultCheck instead of checked which after onClick would produce the map is undefined error

最佳答案

getAllFlavours 中,我不知道您是否应该从 api 接收选中/未选中的值,但是在 getAllFlavours 中设置状态时,您可以将其设置为如下所示:

let flavourLists = { [name] : { isChecked : false } };

并覆盖handleCheckboxChange中选中的值,如下所示:

this.setState({flavors: { ...this.state.flavors ,[name] : { isChecked : true } } })

立即在渲染中访问相应的状态值。

关于javascript - 接收到的没有 true 和 false 属性的 api 响应数组,用于在 React 中动态创建复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56096214/

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