Variable in React is undefined on first render but defined after re-rendering. (Uncaught TypeError: vairable is undefined)

Variable in React is undefined on first render but defined after re-rendering. (Uncaught TypeError: vairable is undefined)

当我尝试显示电影的标题时(App.js 的第 8 行),我收到错误消息“未捕获的类型错误:电影 [0] 未定义”。如果我在第 5 行之后记录变量“电影”,控制台会生成两个日志:首先,将电影记录为空数组,然后将电影记录为包含所有内容的数组,就像我想要的那样。

奇怪的是,如果我删除第 8 行 {movies[0].title} 并保存错误会正常消失,但如果我再次添加它并保存电影标题呈现在屏幕上,就像我正在尝试的那样做。

App.js:

import './App.css';
import useApi from './useApi';

function App() {
  const movies = useApi();
  return (
    <div className="App">
      {movies[0].title}
    </div>
  );    
}

export default App;

我的 useApi returns 一个包含电影列表的数组:

import axios from 'axios';
import { useState, useEffect } from 'react';

const useApi = () => {
    const [movies, setMovies] = useState([]);

    const getData = async () => {
        try {
            const res = await axios(url);
            setMovies(res.data.results);
        } catch (error) {
            return [];
        }
    }

    useEffect(() => {
        getData();
    }, [])

    return movies;
}

export default useApi;

知道如果我打印电影,它会记录一个空数组,但随后它会像我说的那样正常打印,我想我遇到了异步问题,但我不知道是什么。而且它在删除和读取第 8 行时起作用的事实让我更加困惑。

您可能想要使用条件渲染的概念。这样的事情可能会奏效:

import './App.css';
import useApi from './useApi';

function App() {
  const movies = useApi();
  
  if (movies.length) { // conditionally render when the movie list is not empty
    return (
      <div className="App">
        {movies[0].title}
      </div>
    );
  }
  return <div>Loading...</div>   
}

export default App;

因为您的 getData() 函数在 useEffects 挂钩中渲染了两次。您需要检查 if(movies.length>0) 然后输入 return!