首页 > 解决方案 > React State 变量没有更新

问题描述

我有一个子组件列表,它将获取状态变量 this.state.loading 作为道具,它将用于从服务器中提取数据。除了这个状态变量,我还有两个状态变量来控制按钮属性是否刷新。我的问题是单击按钮时组件中的状态变量没有更新。我看到正在调用 REST 调用,但是第二个 REST 调用似乎不起作用。如果我只是在浏览器上调用,则第二次休息调用有效。请检查为什么状态变量没有得到更新以及为什么第二个 Rest api 在浏览器上工作而不是在这个程序中工作。谢谢


class App extends React.Component{
  state ={
    loading:false,
    childload:true,
    placeholder:'',
  };

  enterLoading = () => {
  
    this.setState( ()=> {
      return {
        loading: true,
        placeholder:'Refresh started',
        childload:false,
      };
    });
    
    fetch("api/doScrape")
      .then(response => {
        if (response.status > 400) {
          return this.setState(() => {
            return { placeholder: "Something went wrong during Scraping data" };
          });
        }
        
      });
    

    fetch("api/doCalc")
    .then(response => {
      if (response.status > 400) {
        return this.setState((placeholder) => {
          return { placeholder: "Something went wrong during Vix Calc!" };
        });
      }
    });

    this.setState(() => {
      return {
        loading: false,
        childload:true,
        placeholder:'',
      };
      });
    

    
    
  };

  

  render()
  {
    return (<div className="App">
    <h1> Calculations</h1>
    <Button type="primary" loading={this.state.loading} onClick={() => this.enterLoading()}>
          Refresh
        </Button>{this.state.placeholder}
    <Listing loading={this.state.childload}/> 
    
  </div>);

  }

}

export default App;

标签: reactjsreact-staterest

解决方案


变量工作正常。你只是不知道异步任务是如何工作的。看,您在函数开始时设置了初始状态。在一些 ASYNC 调用之后,您设置这些变量而不是另一个值。这就是您的功能不起作用的原因。

enterLoading = () => {
  
  // THERE
    this.setState( ()=> {
      return {
        loading: true,
        placeholder:'Refresh started',
        childload:false,
      };
    });
    
    fetch("api/doScrape")
      .then(response => {
        if (response.status > 400) {
          return this.setState(() => {
            return { placeholder: "Something went wrong during Scraping data" };
          });
        }
        
      });
    

    fetch("api/doCalc")
    .then(response => {
      if (response.status > 400) {
        return this.setState((placeholder) => {
          return { placeholder: "Something went wrong during Vix Calc!" };
        });
      }
    });

//AND THERE
    this.setState(() => {
      return {
        loading: false,
        childload:true,
        placeholder:'',
      };
      });
    

    
    
  };

推荐阅读