为何在componentDidMount中调用setState未生效?
问题分析与解决方案
这问题我之前踩过同款坑!核心原因是React类组件中的setState是异步操作——它不会立刻更新组件的state,所以你在setState之后马上打印this.state.showValidationModal,拿到的还是更新前的旧值。
为什么会出现这种情况?
React为了优化性能,会把多个setState操作批量合并处理,不会每次调用都立刻触发组件重渲染。你代码里的两次console.log都是在setState的异步更新完成前执行的,所以输出自然都是false。
另外还要提个小细节:类组件的生命周期方法名是小驼峰格式,你代码里写的ComponentDidMount(首字母大写)是错误的,应该改成componentDidMount,不然React不会正确触发这个生命周期哦!
具体解决方法
你可以通过setState的第二个参数(回调函数)来获取更新后的state,这个回调会在state更新完成、组件重渲染后执行:
componentDidMount() { if (this.props.location.search.includes("?token")) { const email = getQueryVariable(this.props.location.search, "email"); const token = getQueryVariable(this.props.location.search, "token"); if (this.state.showValidationModal === false) { console.log("Before", this.state.showValidationModal); // 用回调函数获取更新后的state this.setState({ showValidationModal: true }, () => { console.log("After", this.state.showValidationModal); // 这里会输出true }); } } }
内容的提问来源于stack exchange,提问作者Amine FARHAT
相关产品推荐
相关产品推荐

