繁体   English   中英

在React中设置API数据为state是未定义的,但是API数据是存在的

[英]Setting API data as state in React is undefined, but the API data exists

我的 React state 有一个奇怪的问题。我正在从我的 NodeJS 后端获取数据,它在我的前端 React 应用程序中正确返回。 但是当我尝试用获取的数据初始化 state 时,状态的值为“未定义”,即使我知道数据正确地从后端返回。

这是我的反应代码的重要部分:

const [currentCityData, setCurrentCityData] = useState({});

const fetchData = (cityValue) => {
        axios.get('http://localhost:5000/get-weather', {
            params: {
                cityValue: cityValue
            }
        })
            .then(res => console.log(res?.data?.data[0]))
            .then((res) => setCurrentCityData(res?.data?.data[0]))
            .then(console.log(currentCityData))
            .catch(error => console.log(error))
    };

useEffect(() => {
        fetchData('toronto&country=canada');
    }, []);

我正在获取一个城市的天气。 当我对数据进行控制台日志时,我返回.then(res => console.log(res?.data?.data[0])) inside fetchData ,数据是正确的(它只是一个具有许多天气属性的 object ). 之后的行我设置了我的 state currentCityData ,但是当我在控制台之后立即记录我的currentCityData时,它是undefined

到底我在这里做错了什么?

您不会从第一个 promise then处理程序返回任何东西。 :

  axios.get('http://localhost:5000/get-weather', {
        params: {
            cityValue: cityValue
        }
    })
        .then(res => console.log(res?.data?.data[0])) // <--- here you should return 
        .then((res) => setCurrentCityData(res?.data?.data[0]))
        .then(console.log(currentCityData))
        .catch(error => console.log(error))
};

将您的代码更改为:

  axios.get('http://localhost:5000/get-weather', {
        params: {
            cityValue: cityValue
        }
    })
        .then(res => {console.log(res?.data?.data[0]); return res?.data?.data[0] }) // <--- here you should return 
        .then((res) => setCurrentCityData(res?.data?.data[0]))
        .then(console.log(currentCityData))
        .catch(error => console.log(error))
};

演示:演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM