简体   繁体   中英

ReactJS: re-render not working after component's property is changed

I am having a react issue and I am not seeing where the issue could be. For the code below: I created an accordion component that will display and hide depending upon the value of a state variable called displayForm.

When someone presses a button internal to the InlineListComponent, it should make the form inside InlineListComponent appear. I am passing the this.displayTireAccessories in the displayAction property. I am resetting the state variable for displayForm from false to true, which I thought would then trigger the InlineListComponent to re-render since the displayForm property value has changed. This does not seem to be the case. I added console.log statements to displayAction and the render method for InlineListComponent. I can see where the value is getting updated in the displayForm, however, I am not getting any console.log to print from the InlineListComponent.

What am I missing in the rules for re-rendering that would make this not work?

<InlineListComponent
    orientation="Vertical"
    options={[{name: 'Tires', value: '1'},
        {name: 'Rims', value: '2'},
        {name: 'Hubcaps', value: '3'}]}
    text="name"
    label="Tire accessories (you must enter at least one)"
    key="tireAccessories"
    action={async (item, e) => {
        await this.displayTireAccessories(item);
    }}
    displayAction={async (e) => {
        await this.displayTireAccessories({});
    }}
    displayForm={this.state.displayForm}>
      <TireAccessories addAccessory={this.addAccessory}/>
</InlineListComponent>

this.displayTireAccessories = async (item) => {
  const {dispatch} = this.props;
  await this.setState({displayForm: true});
}

constructor(props){
    super(props);
    this.state = {
        displayForm: true
    }
}

You can't directly await a setState , it doesn't return anything. BUT you can use its callback argument to make it a promise that you can await :

new Promise((resolve) => {
  this.setState(state, resolve)
});

By the way, everytime you have an async function that just awaits one promise at the end of the function, you can discard the async await keywords and just return the promise.

So :

async (e) => {
    await this.displayTireAccessories({});
}

becomes :

(e) => this.displayTireAccessories({})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM