如何解决为什么对状态所做的更改不会在componentDidMount生命周期中显示?
我正在使用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);
}
但是,当我在生命周期方法的末尾运行控制台日志时,它显示帖子和令牌仍然为空。我知道他们正在填充,因为req.data中的帖子显示在我的JSX中。当我在方法内部进行控制台登录时,为什么显示状态为空?
解决方法
反应setState是异步的!
- 反应不能保证状态更改立即生效。
- setState()并不总是立即更新组件。
- 将setState()视为请求而不是立即命令来更新组件。
this.setState((previousState,currentProps) => {
return { ...previousState,foo: currentProps.bar };
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。