使用React Hooks时出现"Cannot read property of undefined"错误

6
我遇到了一个错误:“无法读取未定义的 'map' 属性”,因为电影列表“movies”是未定义的。您能看出我在哪里出了问题吗?非常感谢。

const Dashboard = () => {
  const discoverUrl = 'https://movied.herokuapp.com/discover';
  const [movieList, setMovies] = useState({ movies: [] });

  useEffect(() => {
    const getAllMovies = () => {
      fetch(discoverUrl)
        .then(response => response.json())
         .then(data => setMovies(data))
        }
        getAllMovies()

      }, [])

  return (
    <ul>
      {movieList.movies.map(movie => (
        <li>
          <p>{movie}</p>
        </li>
      ))}
    </ul>
  );
}

export default Dashboard```

TypeError: Cannot read property 'map' of undefined
2个回答

9
你的响应数据可能是一个列表或 undefined,你需要像这样处理它:
setMovies(pre => ({
  ...pre,
  movies: data || []
}))

3

当你设置状态时,即设置setMovies(data),movieList将等于data。因此,你将失去movieList中的movies属性(即没有movieList.movies)。

因此,要么像这样初始化状态

const [movieList, setMovies] = useState([]);

并设置电影数据,代码为 setMovies(data)。

否则可以按以下方式设置状态:

setMovies({ movies: [...data] })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接