Home > Enterprise >  Cann't set the state data from response data
Cann't set the state data from response data

Time:10-28

I'm doing in the axios to get data from webAPI . The problem is state is empty

componentDidMount() {
        uploadFilesService.getFiles().then((response) => {
            this.setState({
                fileInfos: response.data,
            });
            console.log('check 1', response.data)
            console.log('check 2', this.state.fileInfos)

        });
    }

enter image description here

The other project with the same method is OK .

CodePudding user response:

Since state updates are asynchronous, you will not see the updates immediately. So check the state updates in componentDidUpdate

componentDidUpdate(prevProps) { 
 console.log( prevProps.fileInfos) // oldvalue
 console.log( this.state.fileInfos) // new value
}

CodePudding user response:

You can the use second argument of setState

this.setState({
  fileInfos: response.data,
}, () => {
 // do something with the new state
});

From React doc:

The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.

  • Related