react-native - 无法对未安装的组件执行 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;
解决方案
似乎是引用从您的获取中返回的热门电影的问题。将您的 popularMovies 状态设置为results
您的 fetch 的属性,而不是 JSON 的属性。
所以改变:
.then(setPopularMovies)
至...
.then(resJson => setPopularMovies(resJson.results))
然后删除 results 变量并直接引用 PopularMovies。
推荐阅读
- android - 如何在 Android 中以编程方式从外部 SD 卡中删除所有文件或格式化外部 SD 卡?
- javascript - CSS按钮悬停不改变颜色
- sql - 用于存储和计算自定义定价结构的数据库设计
- node.js - 带有承诺放大缓冲区的节点 js getasync
- json - 如何在 Wiremock 请求正文中编码特殊字符?
- azure - 如何使用 Azure 私有 DNS 设置 Aks Ingress
- javascript - 使用变量和 getElementById 和 getElementsByTagName 用 javascript 替换 SRC
- javascript - MVC:发布后数据表不包含任何数据
- python - 覆盖altair的折线图默认分组?
- javascript - Rollup + Babel 转译仍然会创建 `const`