我正在尝试将我的应用程序从redux重写为新的context + hook,但是不幸的是,我很难找到一种好的方法来处理一系列依赖于先前响应的同步副作用。
在当前的redux应用程序中,我大量使用通常通过redux- saga或thunk处理的同步/链接操作和API请求。因此,当返回第一个API请求的响应时,该数据将用于下一个API请求等。
我已经制作了一个自定义钩子“ useFetch”(在此示例中,它并没有太大作用,因为它是简化版本,所以我还必须对其进行一些小的调整才能在codeandbox上使用- 请参见下面的代码)。问题在于由于“钩子规则”,我无法在useEffect钩子内使用自定义钩子。那么,如果您有自己的钩子来获取数据,那么在执行下一个等之前如何等待第一个请求的响应呢?即使我最终放弃了useFetch抽象并创建了一个香草提取请求,如何避免以许多useEffects钩子s肿而告终?是否可以更优雅地完成此操作,还是上下文+挂钩还为时过早,无法与redux saga / thunk竞争来处理副作用?
下面的示例代码非常简单。它应该尝试模拟的是:
这是代码。为useFetch挂钩添加了延迟,以模拟现实世界中的延迟:
import React, { useEffect, useState } from "react"; import { render } from "react-dom"; import "./styles.css"; const useFetch = (url, delay = 0) => { const [data, setData] = useState(null); useEffect(() => { const fetchData = async () => { // const result = await fetch(url, { // method: "GET", // headers: { "Content-Type": "application/json" } // }); //const response = await result.json(); const response = await import(url); setTimeout(function() { setData(response); }, delay); }; fetchData(); }, [url]); return data; }; function App() { const [person, setPerson] = useState(); const [job, setJob] = useState(); const [collegues, setCollegues] = useState(); // first we fetch the person /api/person based on the jwt most likely const personData = useFetch("./person.json", 5000); // now that we have the person data, we use the id to query for the // persons job /api/person/1/jobs const jobData = useFetch("./job.json", 3000); // now we can query for a persons collegues at job x /api/person/1/job/1/collegues const colleguesData = useFetch("./collegues.json", 1000); console.log(personData); console.log(jobData); console.log(colleguesData); // useEffect(() => { // setPerson(useFetch("./person.json", 5000)); // }, []); // useEffect(() => { // setJob(useFetch("./job.json", 3000)); // }, [person]); // useEffect(() => { // setCollegues(useFetch("./collegues.json",1000)); // }, [job]); return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> </div> ); } const rootElement = document.getElementById("root"); render(<App />, rootElement);
正在运行的示例:https : //codesandbox.io/s/2v44lron3n?fontsize=14(您可能需要进行更改- 空格或删除分号-使其起作用)
希望这样的事情(或更好的解决方案)是可能的,否则我将无法从令人敬畏的redux-saga / thunks迁移到context + hooks。
最佳答案: https : //www.youtube.com/watch?v = y55rLsSNUiM
挂钩不会取代您处理异步操作的方式,它们只是您曾经做过的某些事情的抽象,例如调用componentDidMount或处理state等。
componentDidMount
state
在您给出的示例中,您实际上并不需要自定义钩子:
function App() { const [data, setData] = useState(null); useEffect(() => { const fetchData = async () => { const job = await import("./job.json"); const collegues = await import("./collegues.json"); const person = await import("./person.json"); setData({ job, collegues, person }) }; fetchData() }, []); return <div className="App">{JSON.stringify(data)}</div>; }
话虽这么说,也许如果您提供了一个实际的redux-saga或thunks代码示例,并且希望进行重构,那么我们可以看到实现此目标的步骤。
编辑:
话虽如此,如果您仍然想做这样的事情,那么可以看一下:
https://github.com/dai-shi/react-hooks-async
import React from 'react'; import { useFetch } from 'react-hooks-async/dist/use-async-task-fetch'; const UserInfo = ({ id }) => { const url = `https://reqres.in/api/users/${id}?delay=1`; const { pending, error, result, abort } = useFetch(url); if (pending) return <div>Loading...<button onClick={abort}>Abort</button></div>; if (error) return <div>Error:{error.name}{' '}{error.message}</div>; if (!result) return <div>No result</div>; return <div>First Name:{result.data.first_name}</div>; }; const App = () => ( <div> <UserInfo id={'1'} /> <UserInfo id={'2'} /> </div> );
编辑
这是一种有趣的方法https://swr.now.sh/#dependent- fetching