为了账号安全,请及时绑定邮箱和手机立即绑定

在 React 中加载微调器

在 React 中加载微调器

紫衣仙女 2022-08-04 10:04:20
类  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中,以便在数据加载时保持其为真,在数据加载时保持为假
查看完整描述

3 回答

?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

exports class Loading extends Component {

    state = {

        sample: [],

        loading: true

    };


    componentDidMount() {

        this.setState({sample: sample, loading: false});

    }


    render() {

        return (

            <div> 

                {this.state.loading ? 

                    <Spinner /> : <Data />

                }

            </div>

        )

    }

}

检查此方法。


查看完整回答
反对 回复 2022-08-04
?
慕标琳琳

TA贡献1830条经验 获得超9个赞

您可以将状态设置为在发出请求之前,然后设置为返回响应之后(对于成功和失败的响应)。loadingtrueloadingfalse


async componentDidMount() {

  this.setState({

    loading: true

  }):


  this.sampleService

    .getAllSample()

    .then((sample) => {

      this.setState({

        sample, 

        loading: false,

      )}; 

     })

     .catch((err) => {

       console.log(err);

       this.setState({

         loading: false,

       )}; 

     });        

}


查看完整回答
反对 回复 2022-08-04
?
守候你守候我

TA贡献1802条经验 获得超10个赞

您可以将其设置为函数,并在 AJAX 调用之前设置为 ,并将其设置为在接收数据后。您还可以将其设置为在错误情况下async/awaitloadingtruefalsefalse


试试这样的东西


async componentDidMount() {

    this.setState({loading: true});

    try

    {

       const res = await this.sampleService.getAllSample();

       this.setState({sample: res, loading: false);

    }

    catch(err)

    {  

       this.setState({loading:false});

       console.log(err);

    }         

 }


查看完整回答
反对 回复 2022-08-04
  • 3 回答
  • 0 关注
  • 93 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号