无法在已卸载的组件上执行React状态更新。取消useEffect中的所有任务

时间:2020-01-08 10:38:27

标签: react-native memory-leaks undefined react-hooks

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

到目前为止,这是我的代码,很少能正常工作,并且获取返回的是正确的电影数组,但大多数情况下都是发回错误:

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;

returned json

1 个答案:

答案 0 :(得分:0)

似乎是一个问题,涉及从您获取的内容中返回的热门电影。从您的抓取中将您的PopularMovies状态设置为results属性,而不是JSON。

所以改变:

.then(setPopularMovies)

到...

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

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