在 React 中加载微调器


  class Loading extends Component<{},{}> {

      state = {

        sample: [],

        loading: false

      };

      sampleService = new SampleService();


     componentDidMount() {

            this.sampleService

              .getAllSample()

              .then((sample) => {

                this.setState((state) => {

                  return Object.assign(state, { sample: sample });

                });

              })

              .catch((err) => {

                console.log(err);

              });

          }

      }

Component.tsx:


render(){

const {loading} = this.state

}

return(

 {loading ? <Spinner/>: <data>

            )}

我应该在哪里将加载变量放在condentDidMount中,以便在数据加载时保持其为真,在数据加载时保持为假


紫衣仙女
浏览 135回答 3
3回答

一只斗牛犬

exports class Loading extends Component {&nbsp; &nbsp; state = {&nbsp; &nbsp; &nbsp; &nbsp; sample: [],&nbsp; &nbsp; &nbsp; &nbsp; loading: true&nbsp; &nbsp; };&nbsp; &nbsp; componentDidMount() {&nbsp; &nbsp; &nbsp; &nbsp; this.setState({sample: sample, loading: false});&nbsp; &nbsp; }&nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {this.state.loading ?&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Spinner /> : <Data />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; }}检查此方法。

慕标琳琳

您可以将状态设置为在发出请求之前,然后设置为返回响应之后(对于成功和失败的响应)。loadingtrueloadingfalseasync componentDidMount() {&nbsp; this.setState({&nbsp; &nbsp; loading: true&nbsp; }):&nbsp; this.sampleService&nbsp; &nbsp; .getAllSample()&nbsp; &nbsp; .then((sample) => {&nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; sample,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; loading: false,&nbsp; &nbsp; &nbsp; )};&nbsp;&nbsp; &nbsp; &nbsp;})&nbsp; &nbsp; &nbsp;.catch((err) => {&nbsp; &nbsp; &nbsp; &nbsp;console.log(err);&nbsp; &nbsp; &nbsp; &nbsp;this.setState({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;loading: false,&nbsp; &nbsp; &nbsp; &nbsp;)};&nbsp;&nbsp; &nbsp; &nbsp;});&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;}

守候你守候我

您可以将其设置为函数,并在 AJAX 调用之前设置为 ,并将其设置为在接收数据后。您还可以将其设置为在错误情况下async/awaitloadingtruefalsefalse试试这样的东西async componentDidMount() {&nbsp; &nbsp; this.setState({loading: true});&nbsp; &nbsp; try&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;const res = await this.sampleService.getAllSample();&nbsp; &nbsp; &nbsp; &nbsp;this.setState({sample: res, loading: false);&nbsp; &nbsp; }&nbsp; &nbsp; catch(err)&nbsp; &nbsp; {&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;this.setState({loading:false});&nbsp; &nbsp; &nbsp; &nbsp;console.log(err);&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript