状态没有得到使用反应钩子更新?

时间:2019-05-09 12:57:20

标签: jquery html redux axios react-hooks

我为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);
}

有人可以帮助我更新状态吗?

2 个答案:

答案 0 :(得分:0)

首先,当您调度动作时:

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

您没有发送url属性,因此减速器中的url道具未定义

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

第二,我认为您在调用fetching之前分派了fetch操作,否则您将看不到应用程序中的加载效果

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

答案 1 :(得分:0)

我认为您忘记了在调度操作中包含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;
};