繁体   English   中英

useReducer 没有使用 useEffect 更新状态

[英]useReducer is not updating the sate with useEffect

I want to fetch data using useReducer and useEffect getPeople is a function that return the result from https://swapi.dev/documentation#people when i console log results the data is fetching correctly but the state is not updated.

我的功能组件:

  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 />
          </>
          }
        </>
      );
    }

我的减速机 function:

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;
  }
};

TLDR ;

您需要将异步操作包装在 IIFE 中:

useEffect(() => {
    (async() => {
        const { results } = await getPeople();
        dispatch({ type: FETCH_PEOPLE, payload: results });
    })();
}, []);

详情
如果您在 typescript 中执行 OP 版本,则会出现如下错误:

Argument of type '() => Promise<void>' is not assignable to parameter of type 'EffectCallback'

useEffect挂钩期望返回清理 function(可选)。 但是,如果我们go领先于OP的版本,Async ZC1C42526851B5151B5074C174C174C174C174F14F14F14F14F14F14 FERKINE MAKEN BABLACK ZC1C1C1C425268EF1AB514EF1AB51AB51AB51AB51AB51AB51AB51AB51AB51ABERINF1ABERINF1AB51AB51ARIN4F1ABER。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM