我想使用 useReducer
和 useEffect
获取数据
getPeople
是一个从 https://swapi.dev/documentation#people
返回结果的函数
当我控制台日志 results
数据正确获取但状态未更新。
我的功能组件:
export default function App () {
const [state, dispatch] = useReducer(reducer, initialSate);
useEffect(async () => {
const { results } = await getPeople();
dispatch({ type: FETCH_PEOPLE, payload: results });
}, []);
return (
<>
<GlobalStyles/>
{state.loading
? <Loader size={'20px'} />
: <>
<Search></Search>
<People />
</>
}
</>
);
}
我的减速器功能:
export const reducer = (state = initialSate, action) => {
switch (action.type) {
case FETCH_PEOPLE:
return {
...state,
loading: false,
results: action.payload,
counter: state.counter
};
case INCREMENT_COUNTER:
return {
...state,
loading: true,
counter: increment(state.counter)
};
case DECREMENT_COUNTER:
return {
...state,
loading: true,
counter: decrement(state.counter)
};
default:
return state;
}
};
答案 0 :(得分:1)
TLDR;
您需要将异步操作包装在 IIFE 中:
useEffect(() => {
(async() => {
const { results } = await getPeople();
dispatch({ type: FETCH_PEOPLE, payload: results });
})();
}, []);
详情:
如果您在打字稿中执行 OP 版本,则会出现如下错误:
Argument of type '() => Promise<void>' is not assignable to parameter of type 'EffectCallback'
useEffect
钩子期望返回一个清理函数(可选)。但是如果我们继续使用 OP 的版本,异步函数会让回调函数返回一个 Promise。