React Native Redux中getKey函数等待friendExist状态更新问题
解决方法:让getKey等待friendExist的状态更新
这个问题我太熟了!核心原因就是friendExist是异步操作——不管它是在调用后端接口、操作数据库还是更新Redux这类状态管理库的状态,状态更新都不会立刻同步完成。你紧接着调用getKey的时候,this.props.exist还停留在初始的false,自然达不到预期效果。
下面给你两种最常用的解决方案,根据你的实际场景选就行:
方案1:如果friendExist返回Promise(推荐,更直观)
如果你的friendExist方法内部用了async/await或者本身就返回一个Promise(比如调用fetch、axios这类异步API),直接在componentDidMount里用await等待它完成:
async componentDidMount(){ const uid = 'MZdKuFpGmGRntb0nyF4PO0f6kco1'; // 等待friendExist的异步操作全部完成,确保exist状态更新 await this.props.friendExist(uid); // 现在调用getKey,就能拿到更新后的exist值了 this.props.getKey(this.props.exist); // ...其他后续代码 }
方案2:用componentDidUpdate监听状态变化
如果friendExist是通过Redux、MobX这类状态管理工具更新props,没法直接用Promise等待,那就利用React的componentDidUpdate生命周期钩子,监听exist的变化:
componentDidMount(){ const uid = 'MZdKuFpGmGRntb0nyF4PO0f6kco1'; this.props.friendExist(uid); // ...其他初始化代码 } componentDidUpdate(prevProps){ // 只在exist从false变为true的时候触发getKey,避免无限循环 if (prevProps.exist === false && this.props.exist === true) { this.props.getKey(this.props.exist); } }
⚠️ 注意:用componentDidUpdate的时候一定要加条件判断!不然如果getKey又会触发props更新,会导致componentDidUpdate无限重复调用。
内容的提问来源于stack exchange,提问作者Japaleno
相关产品推荐
相关产品推荐

