如何在React中使用useReducer钩子与异步数据?



我试图使用useReducer钩子从API获取数据,然后更新状态。由于这是一个小项目,我尽量避免使用useContext,而只是传递分派函数作为道具。

我之前是如何做到的是使用一个正常的减速机来操纵状态,和一个asyncReducer来获取数据,但是我不知道如何使用这两个在一起。感谢任何指导。我将提供一个链接到下面的完整代码。只需访问repo并点击句号键(.)即可查看它。要查看的主要文件有App.js、reducer.js和letters.jsx

[] https://github.com/robert-levy/cocktail-finder

从之前的应用程序中检查代码,我不确定这将工作,但让我们看看。修改你所需要的,以反映我在这里的内容。

import { reducer, asyncReducer initialState } from './state/reducer'
const App = () => {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<div className="App">
<NavigationBar />
<Container>
<Row>
<Letters dispatch={asyncReducer(dispatch)} />
</Row>
<Row className="justify-content-center">
<SearchBar />
</Row>
<Row>
<Cocktails />
</Row>
</Container>
</div >
);
}

最新更新