首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >useState不适用于对象数组

useState不适用于对象数组
EN

Stack Overflow用户
提问于 2022-10-25 14:58:12
回答 2查看 37关注 0票数 0

我正在做一个小的天气应用程序使用的反应。我打算将useState钩子用于对象数组。通过一个对象数组- latLongStore,我进行多个axios get调用来获取不同城市的天气数据。fetch部分运行良好,但是DOM中没有显示weatherData值。它有正确的对象数量,但似乎不包含任何值。下面是我的代码:

代码语言:javascript
复制
...
const latLongStore = [
  { latitude: 23.8315, longitude: 91.2868, title: "Agartala", color: "#299617", code: 'VEAT' },
  { latitude: 23.0225, longitude: 72.5714, title: "Ahmedabad", color: "#299617", code: 'VCBI' },
...
]

const initialData = {
    city: '',
    latitude: 0,
    longitude: 0,
    max_temperature: 0,
    min_temperature: 0
}

function TableView(props) {
    const [weatherData, updateWeatherData] = useState([initialData]);

    useEffect(() => {
        
            latLongStore.forEach((latLong) => {
                axios.get(`api-url`).then((response) => {

                    const fetchedData = {
                        city: latLong.title,
                        latitude: response.data.latitude,
                        longitude: response.data.longitude,
                        max_temperature: response.data.daily.temperature_2m_max[0],
                        min_temperature: response.data.daily.temperature_2m_min[0]
                    }

                    console.log(fetchedData);

                    updateWeatherData(weatherData => [...weatherData, fetchedData]);
                })
            })
    }, []);

    switch (weatherData.length) {
        default:
            return (
                <div>
                    <br />
                    <br />
                    <br />
                    <br />

                    LOADING...
                    {weatherData.length}
                </div>
            )
        // weatherData contains 62 objects after fetch but no values show up in DOM
        case 62:
            return (
                <div>
                   <br />
                    <br />
                    <br />
                    <br />
                    { weatherData.forEach((data) => {
                        <div>
                            { data.city } : { data.latitude }, { data.longitude }
                        </div>
                    }) }
                </div>
            )
        // default:
        //     return (
        //         <div>
        //             <br />
        //             <br />
        //             <br />
        //             <br />
        //             LOADING...
        //         </div>
        //     )
    }

}

export default TableView;

这是输出:

  • 在上涨的特定时刻

  • weatherData.length达到62

之后

有人能告诉我如何在DOM中显示weatherData值吗?

EN

回答 2

Stack Overflow用户

发布于 2022-10-25 15:42:40

您的forEach函数实际上什么也不做。它只是在数组中循环,仅此而已。您需要使用Array.map()并使回调函数返回一些内容。像这样(没有测试):

代码语言:javascript
复制
{
  weatherData.map((data) => {
    return (<div>
      {data.city} : {data.latitude}, {data.longitude}
    </div>)
  })
}
票数 1
EN

Stack Overflow用户

发布于 2022-10-25 15:40:45

注意:我已经删除了片段中的API请求,否则代码片段将无法工作。(很明显,您可以将它放回useEffect中)

我建议您不要依赖于结果数组的长度,不依赖于。而是关注请求是否正在加载。

代码语言:javascript
复制
const { useState, useEffect } = React;

const latLongStore = [{
    latitude: 23.8315,
    longitude: 91.2868,
    title: "Agartala",
    color: "#299617",
    code: 'VEAT'
  },
  {
    latitude: 23.0225,
    longitude: 72.5714,
    title: "Ahmedabad",
    color: "#299617",
    code: 'VCBI'
  }
]

// const initialData = {
//     city: '',
//     latitude: 0,
//     longitude: 0,
//     max_temperature: 0,
//     min_temperature: 0
// }

function TableView(props) {
  const [weatherData, updateWeatherData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);


  useEffect(() => {
    // Set Loading to true before requests
    setIsLoading(true);
    latLongStore.forEach((latLong) => {
      // I have removed the request as I can't access whatever API being used
      const fetchedData = {
        city: latLong.title,
        latitude: latLong.latitude,
        longitude: latLong.longitude,
        max_temperature: 5,
        min_temperature: 2
      };

      // console.log(fetchedData);

      updateWeatherData(weatherData => ([
        ...weatherData,
        fetchedData
      ]));
    })
    // Set Loading to false after
    setIsLoading(false);
  }, []);

  if (isLoading) {
    return (
      <div >
        <br />
        <br />
        <br />
        <br />
        LOADING...{weatherData.length}
      </div>
    )
  }
  return (
    <div>
      <br />
      <br />
      <br />
      <br />
      {weatherData.map((data, index) => (
        <div key={index}>
          {data.city}, {data.latitude}, {data.longitude}
        </div>
      ))}
    </div>
  )

}


ReactDOM.render(
  <TableView /> ,
  document.getElementById("root")
);
代码语言:javascript
复制
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74196107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档