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

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

無法在反應中訪問獲取響應中的深層嵌套對象

無法在反應中訪問獲取響應中的深層嵌套對象

米脂 2023-11-02 22:52:15
因此,我在 Stack 和 Web 上偶然發現了很多示例,其中從異步獲取調用訪問深層嵌套對象返回未定義。許多答案都解決了其他文章,從而導致了對象和數組的訪問方式。其他人聲稱這是異步操作的原因。但我實在無法理解它。這是數據:base: "stations"clouds: {all: 1}cod: 200coord: {lon: -81.38, lat: 28.54}dt: 1607561322id: 4167147main: {temp: 51.28, feels_like: 45.97, temp_min: 48.99, temp_max: 53.6, pressure: 1021, …}name: "Orlando"sys: {type: 1, id: 5234, country: "US", sunrise: 1607515628, sunset: 1607552963}timezone: -18000visibility: 10000weather: [{…}]wind: {speed: 4.52, deg: 271}這是代碼,注意 useEffect 回調中的 setWeatherDatafunction WeatherDisplay(props){  const [weatherData, setWeatherData] = useState({})  useEffect(() => {    fetch(`http://api.openweathermap.org/data/2.5/weather?q=Orlando&units=imperial&appid=3abd9c2df6a249e8abcf4f812de0a627`)    .then(res => res.json())    .then(data => {      setWeatherData({        data,        name: data.name,        main: data.main,        ...data.main      })    })    .catch(err => console.log(err))  }, [])  return(    <>      <Media style={{backgroundColor: "gray", borderRadius: "5px", height: "5.5rem"}}>        <IconContext.Provider value={{size: "5rem", style:{fontWeight: "200"}, className:"align-self-center"}}>          <TiWeatherPartlySunny />        </IconContext.Provider>          {console.log(weatherData)}          {console.log(weatherData.name)}          {console.log(weatherData.main)}          {console.log(weatherData.temp)}      </Media>    </>  )}https://i.stack.imgur.com/8aEj7.png 這就是首先開始的方式,我只是將WeatherData設置為數據,因為我可以渲染weatherData.name(奧蘭多),但由于某種原因weatherData.main.temp返回錯誤,因為weatherData.main導致未定義。我四處詢問,他們說這是因為承諾并且它是異步的,所以我必須使用條件等等,但這仍然不能解釋它如何能夠訪問weatherData.name。與weatherData.clouds和.sys相同我繼續傳播我想要的對象的值,但我可以想到我的解決方法沒有用的簡單情況。我想知道這是否是反應保存深度嵌套對象的值的方式,但我真的不知道。
查看完整描述

3 回答

?
UYOU

TA貢獻1878條經驗 獲得超4個贊

是的,這是因為異步行為。該weatherData對象將始終存在(最初作為 {},然后在請求完成后使用獲取的數據)。

在初始渲染中,weatherData.namewill equal{}.name將返回 undefined,但不會導致錯誤。

但是,當您運行時,weatherData.main.temp它將 equal {}.main.temp,這意味著您實際上正在調用undefined.temp這將引發錯誤。僅當mainprop 未定義時才會拋出此錯誤,這意味著一旦實際獲取數據,它就應該正常工作。

您可以通過幾種不同的方法來解決這個問題,我推薦以下兩種方法之一:

  1. 如果提取尚未完成,則呈現“正在加載數據...”等的條件渲染。

  2. 條件訪問器。嘗試訪問weatherData.main?.temp而不是weatherData.main.temp. 不確定它是否能在 JSX 內部工作,但假設您使用的是最新版本的 babel ,它可以正確轉換條件分支,那么它應該可以在外部工作。

  3. 您還可以創建一個weatherData定義了預期接口的初始對象,但所有值都設置為undefined.

換句話說,

const initialWeatherData = {

  name: undefined,

  main: {

    temp: undefined,

  }

}

// etc, leaving out most of the object as I'm sure you get what I'm trying to do

// just make sure you define the entire interface


const [weatherData, setWeatherData] = useState(initalWeatherData);


查看完整回答
反對 回復 2023-11-02
?
三國紛爭

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

如果你設置如下


setWeatherData({

    data

})

您的天氣數據將是


{

    data: {

        main: {...},

        name: '...'

        sys: {...}

    }

}

要訪問 main,您應該使用


weatherData.data.main


查看完整回答
反對 回復 2023-11-02
?
慕工程0101907

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

您可以通過此代碼和 API 圖像來理解這個想法。希望對您有幫助

https://img1.sycdn.imooc.com/6543b7e90001cf1b04160305.jpg

import React  from 'react'


class GetData extends React.Component {

    state = {

        data: []


    };


    async componentDidMount() {

        try {

            const url = "http://localhost:8000/blogList";

            const response = await fetch(url);

            const data = await response.json();

            console.log(data);

            this.setState({ data: data.result });

        } catch (err) {

            console.log(err);


        }

    }


    render() {

        const { data } = this.state


        return (


            <div>{

                <ul>

                    {data.map((item, i) => {

                        return <li key={item.id}>{item.title}</li>


                    })}

                </ul>


            }

            </div>



        );

    }

}

export default GetData


查看完整回答
反對 回復 2023-11-02
  • 3 回答
  • 0 關注
  • 202 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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