此.Setstate在reactJS中无法正常工作
我是新来的 我有这样一种状态:此.Setstate在reactJS中无法正常工作,reactjs,Reactjs,我是新来的 我有这样一种状态: state = { isLoading: true, }; 我有这个生命周期功能 componentDidMount() { const { setPageCount, receiveApiData } = this.props.actions; const { isLoading } = this.state; const getData = () => { this.setState({ is
state = {
isLoading: true,
};
我有这个生命周期功能
componentDidMount() {
const { setPageCount, receiveApiData } = this.props.actions;
const { isLoading } = this.state;
const getData = () => {
this.setState({ isLoading: !isLoading });
receiveApiData();
setPageCount();
};
setInterval(() => {
getData();
}, 30000);
}
以下是我试图在render()中返回的内容:
returnisloading?(
):(`Some Code here`)
问题是状态始终为true,我的生命周期方法没有将其更改为false,因此我的应用程序无法呈现false条件。
我不知道该怎么办,有什么建议吗
getData()
中的所有其他内容都正常工作问题在于:
this.setState({ isLoading: !isLoading });
因为isLoading
您正在解构的内容采用以前的值,即它没有采用最新的状态值,因此它不会更新您的isLoading
。您需要做的是:
this.setState({ isLoading: !this.state.isLoading });
这里是演示:问题在这里:
this.setState({ isLoading: !isLoading });
因为isLoading
您正在解构的内容采用以前的值,即它没有采用最新的状态值,因此它不会更新您的isLoading
。您需要做的是:
this.setState({ isLoading: !this.state.isLoading });
演示如下:由于新状态取决于旧状态的值,因此应使用函数形式
setState
this.setState(prevState => ({
isLoading: !prevState.isLoading
}));
官方文档:由于新状态取决于旧状态的值,因此应使用函数形式
setState
this.setState(prevState => ({
isLoading: !prevState.isLoading
}));
正式文件: