亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從使用中的 API 獲取相應的效果和呈現組件

從使用中的 API 獲取相應的效果和呈現組件

呼如林 2022-09-29 15:52:38
我在 React 中渲染基于 API 調用的組件時遇到問題。我在使用中獲取數據效果掛鉤使用數據更新狀態。在 api 獲取所有數據之前,狀態為 null 一段時間,但到那時,組件將使用 null 值進行呈現。這就是我所擁有的:import React, { useEffect, useState } from 'react'import axios from 'axios';import { Redirect } from 'react-router-dom';const Poll = (props) => {const [poll, setPoll] = useState(null);//if found is 0 not loaded, 1 is found, 2 is not found errconst [found, setFound] = useState(0);useEffect(() => {    axios.get(`api/poll/${props.match.params.id}`)        .then(res => {            console.log(res.data);            setPoll(res.data);            setFound(1);        })        .catch(err => {            console.log(err.message);            setFound(2);        });}, [])if(found===2) {    return(        <Redirect to="/" push />    )}else{    console.log(poll)    return (        <div>        </div>    )}}export default Poll這是我的解決方法,但感覺不是應該這樣做的方式。如何設置它,以便等待我的 api 數據返回,然后相應地呈現組件?
查看完整描述

3 回答

?
撒科打諢

TA貢獻1934條經驗 獲得超2個贊

您不需要像 那樣跟蹤 API 調用的狀態。只需檢查輪詢是否存在,也可以創建一個新的狀態變量來跟蹤錯誤。const [found, setFound] = useState(1)


例如,這將呈現一個帶有“加載...”的 div當沒有數據時。請參閱下面的代碼,了解完整的解決方案,if (!poll) { return <div>Loading...</div>}


import React, { useEffect, useState } from 'react'

import axios from 'axios';

import { Redirect } from 'react-router-dom';


const Poll = (props) => {


   const [poll, setPoll] = useState(null);


   const [hasError, setHasError] = useState(false);



   useEffect(() => {

     axios.get(`api/poll/${props.match.params.id}`)

        .then(res => {

            console.log(res.data);

            setPoll(res.data);

        })

        .catch(err => {

            console.log(err.message);

            setHasError(true)

        });

  }, [])



  if(!poll) {

    console.log('data is still loading')

    return(

       <div>Loading....</div>

    )

   }


  if (hasError) {

   console.log('error when fetching data');


   return (

     <Redirect to="/" push />

   )

 }



 return (

   <div>

    {

      poll && <div>/* The JSX you want to display for the poll*/</div>

    }

   </div>

 );

}


export default Poll


查看完整回答
反對 回復 2022-09-29
?
心有法竹

TA貢獻1866條經驗 獲得超5個贊

在您的 than 中,嘗試使用過濾器:

setPoll(poll.filter(poll => poll.id !== id));

確保用您的識別器替換 id


查看完整回答
反對 回復 2022-09-29
?
慕姐4208626

TA貢獻1852條經驗 獲得超7個贊

標準方法是為加載和錯誤狀態設置其他變量,如下所示


const Poll = (props) => {


    const [poll, setPoll] = useState(null);

    const [loading, setLoading] = useState(false);

    const [error, setError] = useState(false);



    useEffect(() => {

        setLoading(true);

        axios.get(`api/poll/${props.match.params.id}`)

            .then(res => {

                console.log(res.data);

                setPoll(res.data);

            })

            .catch(err => {

                console.log(err.message);

                setError(true);

            })

            .finally(()=> {

                setLoading(false);

            };

    }, [])



    if(error) return <span>error<span/>

    if(loading) return <span>loading<span/>

    return (

        <div>

           // your poll data


        </div>

    )

}


查看完整回答
反對 回復 2022-09-29
  • 3 回答
  • 0 關注
  • 105 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號