为什么我对状态的更改不会显示在我的组件 DidMount 生命周期中?



我正在使用React构建一个应用程序,对于我的主页,我在componentDidMount生命周期中设置状态:

export default class HomePage extends Component {
state = {
posts: [],
token: '',
};
//Display posts when homepage renders
componentDidMount() {
//If token exists, run lifecycle event
if (this.props.location.state.token) {
this.setState({ token: this.props.location.state.token });
}
Axios.get('http://localhost:3000/api/posts/all')
.then((req) => {
this.setState({ posts: req.data });
})
.catch((err) => {
console.log(err.message);
throw err;
});
console.log(this.state);
}

然而,当我在生命周期方法结束时运行控制台日志时,它显示posts和token仍然是空的。我知道它们正在被填充,因为req.data中的帖子出现在我的JSX中。为什么当我在方法内部控制台日志时,它显示状态为空?

React setState是异步的!
  • React不能保证立即应用状态更改
  • setState((并不总是立即更新组件
  • 将setState((视为一个请求,而不是一个立即更新组件的命令
this.setState((previousState, currentProps) => {
return { ...previousState, foo: currentProps.bar };
});

最新更新