首页 > 解决方案 > 无法对未安装的组件执行 React 状态更新。取消 useEffect 中的所有任务

问题描述

我看到的是一个常见错误,我尝试了不同的解决方案但没有结果。

到目前为止,这是我的代码,很少工作,并且 fetch 返回了一个正确的电影数组,但大多数时候都发回了一个错误:

import React, { useState, useEffect } from "react";
import { Text, View, Image, ScrollView, ActivityIndicator } from "react-native";

function Dashboard() {
   const [loading, setLoading] = useState(true);
   const [popularMovies, setPopularMovies] = useState([])

   const popularMoviesUrl =
       ".....";

   const fetchMovies = () => {
    fetch(popularMoviesUrl)
     .then(res => res.json())
     .then(setPopularMovies)
     .then(console.log(popularMovies));
   };

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

   const { results } = popularMovies;

      return loading ? (
         <View style={styles.loader}>
            <ActivityIndicator size="large" color="#dcae1d" animating />
         </View>
   ) : (
      <ScrollView horizontal style={styles.container}>
         {results.map(movie => (
            <View key={movie.id}>
            <Text style={styles.container}>{movie.title}</Text>
            <Image
                style={styles.poster}
                source={{
                    uri: `https://image.tmdb.org/t/p/w500${movie.poster_path}`
            }}
          />
        </View>
      ))}
      <Text>thfh</Text>
    </ScrollView>
   );
  }

  export default Dashboard;

返回的json

标签: react-nativememory-leaksundefinedreact-hooks

解决方案


似乎是引用从您的获取中返回的热门电影的问题。将您的 popularMovies 状态设置为results您的 fetch 的属性,而不是 JSON 的属性。

所以改变:

.then(setPopularMovies)

至...

.then(resJson => setPopularMovies(resJson.results))

然后删除 results 变量并直接引用 PopularMovies。


推荐阅读