可以在api fetch之后对未填充组件上的反应状态更新执行反应状态更新
我正在编写一个React组件,其中从API获取数据,然后用状态刷新组件,但是由于某些原因,我总是会遇到此错误:
警告:无法在未填充组件上执行React状态更新。这是一个无操作,但表示您的应用程序中的内存泄漏。要修复,请在使用效率清理功能中取消所有订阅和异步任务。 在CollectionContainer(http:// localhost:3000/static/js/bundle.js:1632:102)
我尝试了解决类似问题的解决方案,但没有奏效,请忍受我,我是新手,我是新手
code
import React from "react";
import { useState } from "react";
function CollectionContainer(props) {
//STATE
const [FilesAPIfetched, setFilesAPIfetched] = useState(false);
function RefreshDataDatasets() {
console.log("Refreshed collections data");
setFilesAPIfetched(true);
}
const files = ["test"];
const COLLECTION_ID = props.children.id;
//API CALL
let API_CALL_FILES = `http://xxx.yyy/${COLLECTION_ID}/files/`;
fetch(API_CALL_FILES)
.then((res) => res.json())
//.then((data) => console.log(data));
.then((data) => {
for (let i = 0; i < data.length; i++) {
files[i] = data[i];
}
console.log(files);
RefreshDataDatasets();
});
I am writing a React component where I fetch data from an API and then I refresh the component with states, but for some reasons I always get this error:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
at CollectionContainer (http://localhost:3000/static/js/bundle.js:1632:102)
I tried solutions to similar questions but nothing worked, please bear with me, I'm new to React
Code
import React from "react";
import { useState } from "react";
function CollectionContainer(props) {
//STATE
const [FilesAPIfetched, setFilesAPIfetched] = useState(false);
function RefreshDataDatasets() {
console.log("Refreshed collections data");
setFilesAPIfetched(true);
}
const files = ["test"];
const COLLECTION_ID = props.children.id;
//API CALL
let API_CALL_FILES = `http://xxx.yyy/${COLLECTION_ID}/files/`;
fetch(API_CALL_FILES)
.then((res) => res.json())
//.then((data) => console.log(data));
.then((data) => {
for (let i = 0; i < data.length; i++) {
files[i] = data[i];
}
console.log(files);
RefreshDataDatasets();
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用效果挂钩在页面渲染后调用API请求。
效应挂钩类似于componentDidmount和componentDidupdate在React中构建类组件时,但是当您使用功能组件时,需要使用效应钩。
You can use the Effect Hook to call the API request after the page renderization.
Effect Hook is similar to ComponentDidMount and componentDidUpdate when you build Class Components in React, but when you use Functional Components, you need to use Effect Hook.