反应Web应用程序有条件的应用程序加载不起作用

时间:2019-01-11 23:20:54

标签: reactjs

我正在学习反应,并能够进行设置。使用create-react-app反应项目。现在,我正在尝试学习在用户输入关键字时添加微调器,并且必须等待一段时间才能加载结果。

class App extends React.Component {
    state = { result: [] ,loading:null};

    OnSearchSubmit = async (email) =>{
       this.state.loading = true;
       try 
       {
           const response =  await fetch(‘/info’,{
            method:'post',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
                },
            });
            const body = await response.json();      
            this.setState({loading:false,  result: body});
        }catch(err){
            console.log(err);
        }
    };
     render (){
        return (
            <div className="ui container" style={{ marginTop: '10px'}}>
                <SearchBar onSubmit={this.OnSearchSubmit}/>
                {
                     this.state.loading === true ? 
                     <LoadingSpinner/> : 
                    <PrjList plist={result}/>
                }
            </div>
        );
    }
}

结果到达时,它将列出我的plist项目。但这并没有显示等待中的微调器。我已经跟踪了status.loader值,它正确显示了值的变化,但没有显示微调器。有人可以找到我可能忽略的地方

tutorial followed for adding spinner

1 个答案:

答案 0 :(得分:1)

要更新组件状态,您应使用setState

/* ... */
state = { result: [] ,loading: false};

    OnSearchSubmit = async (email) =>{
       /* HERE */
       this.setState({ loading: true });

       try 
       {
           const response =  await fetch(‘/info’,{
            method:'post',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
                },
            });
            const body = await response.json();      
            this.setState({loading:false,  result: body});
        }catch(err){
            console.log(err);
        }
    };

/* ... */

请记住setState是异步的,因此,您可以改进setState结束后调用方法的代码:

OnSearchSubmit = email => {
  this.setState({ loading: true }, () => { this.fetchInfo(email) });
}

fetchInfo = email => {
  try {
    /* ... rest of the code */
  } catch...
}