gpt4 book ai didi

javascript - 在 HOC 中包装的 useEffect 中获取数据时组件的无限渲染

转载 作者:行者123 更新时间:2023-12-04 03:22:28 25 4
gpt4 key购买 nike

我正在尝试做的事情:

  1. 从我的组件中获取 useEffect 中的数据
  2. 从 HOC 更新加载状态
  3. 返回包装组件/显示数据

App.js

import axios from "axios";
import { useEffect, useState } from "react";
import withFetch from "./withFetch";

const App = ({ setLoading }) => {
const [data, setData] = useState([]);

useEffect(() => {
setLoading(true);

async function fetchData() {
await axios
.get("https://jsonplaceholder.typicode.com/todos")
.then((res) => {
setData(res.data);
setLoading(false);
});
}

fetchData();
}, []);

return (
<div>
{data.map((item) => (
<p>{item}</p>
))}
</div>
);
};

export default withFetch(App);

withFetch/HOC:

import React, { useState } from "react";

const withFetch = (WrappedComponent) => {
const WithFetch = (props) => {
const [isLoading, setLoading] = useState(false);

if (isLoading) return <h1>Loading..</h1>;

return <WrappedComponent setLoading={setLoading} {...props} />;
};

return WithFetch;
};

export default withFetch;

出了什么问题:

  • 从/到 HOC 和我的组件的无限循环

我在 CodeSandbox 中做了一个非常简单的演示来演示我的问题:https://codesandbox.io/s/reverent-cache-bb044?file=/src/App.js

最佳答案

一旦 App 调用 setLoading(true),WithFetch 就不再渲染 WrappedComponent,因此 App 被卸载。

然后最终请求成功,并调用 setLoading(false),它呈现一个应用程序,该应用程序调用另一个请求。

相反,我认为您想将获取代码与 isLoading 状态放在一起。

// withFetch.jsx
// The withFetch HOC knows how to conditionally display a component
// depending on whether data has been fetch, and actually fetches.
// But, it doesn't know _where_ the data came from (because presumably
// you will want to reuse this for different data sets)

const withFetch = (WrappedComponent) => {
const WithFetch = (props) => {
const [isLoading, setLoading] = useState(false);
const [data, setData] = useState([]);

useEffect(() => {
setLoading(true);

async function fetchData() {
await axios.get(props.url).then((res) => {
setData(res.data);
setLoading(false);
});
}

fetchData();
}, [props.url]);

if (isLoading) {
return <h1>Loading..</h1>;
} else {
return <WrappedComponent data={data} {...props} />;
}
};

return WithFetch;
};


// Display.jsx
// The Display component knows how to display data after it has
// been fetched, but knows nothing about how to fetch the data
// or where it comes from.

const Display = ({ data }) => {
return (
<div>
{data.map((item) => (
<p>{item}</p>
))}
</div>
);
};

export default withFetch(Display);


// App.jsx
// The App component renders the Display component and
// provides the URL where data comes from

const App = () => {
return <Display url="https://jsonplaceholder.typicode.com/todos" />;
};

// do not wrap App with withFetch

关于javascript - 在 HOC 中包装的 useEffect 中获取数据时组件的无限渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68229690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com