首页 > 解决方案 > 类型错误。无法反应属性“0”未定义

问题描述

我正在尝试从 API 显示电影的类型

这是回复

在此处输入图像描述

我收到此错误(下图),我认为这是因为页面在请求能够将其插入 useState 之前尝试显示流派(我 useState 存储 api 响应,然后获取当前状态并显示它到页面)

在此处输入图像描述

这是我从 useState 呈现数据的地方

在此处输入图像描述

标签: reactjs

解决方案


You need to check for movieDetails to be there to actually render it.

I suggest you do something like this:

const MovieDetails = (props) => {
  const [movieDetails, setMovieDetails] = useState(null)

  useEffect(() => {

   // get your data asynchronously

   setMovieDetails(data)

  }, []) // when the component mounts

  return !movieDetails
    ? <div>loading...</div>
    : (
      <div>
        <h1>{movieDetails.title}</h1>
        <h3>{movieDetails.overview}</h3>
        {movieDetails.genres[0] && <h1>{movieDetails.genres[0].name}</h1>}
        <Link to="/">Home</Link>
      </div>
    )

}

Also, you can create another state in case there are errors while fetching the data. And bonus points: abstracting this away in a general hook called i.e. useFetchData that returns something like { data, loading, error }


推荐阅读