gpt4 book ai didi

react-native - 如何在 componentDidMount 上更改 React Native 中的状态?

转载 作者:行者123 更新时间:2023-12-02 04:40:14 32 4
gpt4 key购买 nike

我有以下警告:Warning: setState(...): Can only update a mounted or mounting component.这通常意味着您在未安装的组件上调用了 setState() 。这是一个空操作。请检查 Home 组件的代码。

export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
loaded: false,
failed: false
};
}
componentWillMount() {
Actions.auth();
}
componentDidMount() {
Actions.loadUser.completed.listen(this.onLoadUserCompleted.bind(this));
Actions.goHome.listen(this.onGoHome.bind(this));
Actions.logout.listen(this.onLogout.bind(this));
}
onLoadUserCompleted(user) {
let currentUser = DataStore.getCurrentUser();
this.setState ({ loaded: true }); // <=============
}
}

最佳答案

componentDidMount() 可以通过 setState 改变状态。我们的代码中有很多这样的东西,请参见下面的示例。我猜 setState() 的另一个调用会导致这个警告,也许在另一个 View /组件中? (或者您的组件由于某种原因意外卸载)

  constructor(props) {
super(props);

this.state = {
runAfterInteractions: false,
};
}

componentDidMount() {
InteractionManager.runAfterInteractions(() => {
this.setState({
runAfterInteractions: true,
});
});
}

render() {

if(!this.state.runAfterInteractions) return null;
....

关于react-native - 如何在 componentDidMount 上更改 React Native 中的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38171577/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com