React:是否可以停止代码“阅读”,直到组件收到新的道具?

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


它是类组件。该按钮在 Props 示例中: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>


幕布斯6054654
浏览 153回答 2
2回答

慕容森

我建议使用Promisethis.state = {&nbsp; &nbsp;selectedDates: [Date],&nbsp;&nbsp; &nbsp;currentType: null,&nbsp;}<button&nbsp; &nbsp; onClick={() => {&nbsp; &nbsp; &nbsp; &nbsp; this.props.onCreateClick(this.state.selectedDate).then(types => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let newType = types[types.length - 1];&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selectedDates: [],&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; currentType: newType.id&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; }).catch(error => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //handle error&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }}>Create</button>和onCreateClick函数返回无极其中reslove您收到新的类型,然后你处理它们在你的状态组件。如果您希望可以将此代码更改为async\await,则与 promise 相同。

隔江千里

我会返回类似布尔值的内容onCreateClick()并将其存储在变量中。然后您可以轻松检查该变量是否已设置。this.state = {&nbsp; &nbsp;selectedDates: [Date],&nbsp;&nbsp; &nbsp;currentType: null,&nbsp;}handleOnClick = () => {&nbsp; const isHandled = this.props.onCreateClick(this.state.selectedDate)&nbsp; if(isHandled){&nbsp; &nbsp; let newType = this.props.types[this.props.types.length - 1];&nbsp;&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp;selectedDates: [],&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;currentType: newType.id&nbsp; &nbsp; })&nbsp; }}<button type="button" onClick={() => this.handleOnClick()}>Create</button>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript