gpt4 book ai didi

javascript - react : Is it possible to stop code 'reading' until component will receive new props?

转载 作者:行者123 更新时间:2023-11-28 03:23:42 25 4
gpt4 key购买 nike

我有一个组件,它有一个按钮,可以在单击时创建 newType 并将其设置为状态。types 来自父组件的外部。如何在 this.props.onCreateClick(this.state.selectedDate) 运行时停止运行代码并等到我收到更新的 types 以便当我更新时types 我可以运行下一行吗?

它是类组件。那个按钮在里面 Prop 示例: props: types = [{id: 1, name: 'One'}, {id: 2, name: 'Two'}]

this.state = {
selectedDates: [Date],
currentType: null,
}

<button
onClick={(e) => {
this.props.onCreateClick(this.state.selectedDate)
let newType = this.props.types[this.props.types.length - 1];

this.setState({
selectedDates: [],
currentType: newType.id
})
}}

>Create</button>

最佳答案

我建议使用Promise

this.state = {
selectedDates: [Date],
currentType: null,
}

<button
onClick={() => {
this.props.onCreateClick(this.state.selectedDate).then(types => {
let newType = types[types.length - 1];

this.setState({
selectedDates: [],
currentType: newType.id
});
}).catch(error => {
//handle error
});

}}

>Create</button>

并且 onCreateClick 函数返回 Promise 您收到的 reslove 新类型,然后在组件的状态下处理它们。

如果您希望将此代码更改为 async\await,与 Promise 的工作方式相同。

关于javascript - react : Is it possible to stop code 'reading' until component will receive new props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58876344/

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