如何在React js中点击按钮再次获取数据?

问题描述 投票:0回答:1

我创建了一个 HOC 或容器组件,从中获取数据并将其发送到子组件。我还使用react-router-dom库进行路由。

我正在使用这样的 HOC 组件

<BrowserRouter>
    <Routes>
      <Route path={'/'} element={<HOC Component={App} />} />
    </Routes>
  </BrowserRouter>

我像这样向子组件发送数据

export const HOC = ({ Component }) => {
  const fetchData = () => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const data = {
          message:
            'Data fetched successfully' + Math.floor(Math.random() * 100),
        };
        return resolve(data);
      }, 2000); // Simulating a delay of 2 seconds
    });
  };
  return (
    <div>
      <If condition={fetchData()}>
        <Fallback>Loading data ...</Fallback>
        <Then>
          {(data) => (
            <>
              <span>parent component your data:{JSON.stringify(data)}</span>
              <Component data={data} />
            </>
          )}
        </Then>
        <Else>{(error) => <span>Failed to load data because </span>}</Else>
      </If>
    </div>
  );
};

现在的问题是我的子组件中有一个CTA,点击它我想再次获取数据,有什么办法使用react-router-dom ??。我想重新渲染HOC,以便它再次获取并将新数据发送给子组件

这是我的代码

https://stackblitz.com/edit/vitejs-vite-gtdrmg?file=src%2FApp.tsx,src%2Findex.css,src%2Fmain.tsx,src%2Fhoc.tsx,src%2FApp.css&terminal=开发

我认为将

fetchData
传递给子组件并进行操作的一种方法,但我认为父组件没有正确的数据..

javascript reactjs
1个回答
0
投票

// hoc.tsx 文件

import React, { useState, useEffect } from 'react';
import { If, Fallback, Then, Else } from 'react-if';

interface Props {
  Component: React.ComponentType<any>;
}

export const HOC: React.FC<Props> = ({ Component }) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  const fetchData = () => {
    setLoading(true);
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const newData = {
          message:
            'Data fetched successfully ===>' + Math.floor(Math.random() * 100),
        };
        setData(newData); // Update the data state with the new data
        setLoading(false);
        return resolve(newData);
      }, 2000);
    });
  };

  useEffect(() => {
    fetchData();
  }, []); // Fetch data when component mounts

  return (
    <div>
      <If condition={!loading}>
        <Then>
          <Component data={data} fetchAgain={fetchData} />
        </Then>
        <Else>
          <Fallback>Loading data ...</Fallback>
        </Else>
      </If>
    </div>
  );
};

// App.tsx 文件

import React from 'react';
import { useState } from 'react';
import './App.css';

function App({ data, fetchAgain }) {
  const handleClick = () => {
    console.log(fetchAgain)
    fetchAgain();
  };
  
  return (
    <>
      <h1>Child component {JSON.stringify(data)}</h1>
      <button onClick={handleClick}>Again fetch</button>
    </>
  );
}

export default App;


Try this if this help you, give me up..
© www.soinside.com 2019 - 2024. All rights reserved.