状态没有使用React Hook进行更新



我为API调用创建了一个自定义挂钩。每当发生API调用时,我都试图将一个标志值设置为false。一旦我得到响应,标志应更改为false。我已经在API调用中派遣操作,但是我无法更新状态值。

import { useEffect, useReducer } from "react";
import fetch from "axios";
const useApiHook = (url, reducer) => {
    const [state, dispatch] = useReducer(reducer, { loading: false });
    useEffect(() => {
        fetch(url)
            .then(dispatch({ type: "fetching", loading: true }))
            .then(res => res.data)
            .then(data => dispatch({ type: "success", loading: false, data }))
            .catch(err => dispatch({ type: "fail", loading: false, err }));
    }, [url]);
    return state;
};
}
const Reducer = (state, action) => {
    const { url, data, err } = action;
    const currentState = state[url];
    console.log("action", action);
    console.log("state", state.loading);
    switch (action.type) {
        case "fetching":
            return {
                ...state,
                [url]: { ...currentState, loading: action.loading }
            };
        case "success":
            return {
                ...state,
                [url]: { ...currentState, loading: action.loading, data }
            };
        case "fail":
            return {
                ...state,
                [url]: { ...currentState, loading: action.loading, err }
            };
        default:
            return state;
    }
};
const Comp = () => {
    const url = "https://randomuser.me/api/";
    const sample = useApiHook(url, Reducer);
}

任何人都可以帮助我更新状态吗?

首先,当您派遣操作时:

dispatch({ type: "success", loading: false, data })

您没有发送url属性,因此您的还原器中的url Prop不确定

const { url, data, err } = action;
// url is undefined

其次,我认为您在调用fetch之前派遣fetching操作,否则您将不会在应用程序中看到加载效果

 dispatch({ type: "fetching", loading: true })
 fetch(url)
      .then(res => res.data)
      .then(data => dispatch({ type: "success", loading: false, data }))
      .catch(err => dispatch({ type: "fail", loading: false, err }));

我认为您忘了在派遣操作中包括URL参数

const useApiHook = (url, reducer) => {
    const [state, dispatch] = useReducer(reducer, { loading: false });
    useEffect(() => {
        fetch(url)
            .then(dispatch({ type: "fetching", loading: true }))
            .then(res => res.data)
            .then(data => dispatch({ type: "success", loading: false, data, url }))
            .catch(err => dispatch({ type: "fail", loading: false, err, url }));
    }, [url]);
    return state;
};

相关内容

  • 没有找到相关文章

最新更新