将 React useReducer 转换为 TypeScript

Converting React useReducer to TypeScript

我正在尝试将 useReducer 挂钩转换为 TypeScript, 它作为 useReducer 钩子工作正常,但在 TypeScript 中不行。

这是我的代码,

import * as React from "react";

const JOKE_URL = "https://icanhazdadjoke.com/";

const initialState = { data: null, error: null, loading: true };
type ACTIONTYPE =
    | { type: "fetch" }
    | { type: "data"; data: object }
    | {type: "error"};

function fetchReducer(state: typeof initialState, action: ACTIONTYPE) {
    switch (action.type) {
        case 'fetch':
            return {
                ...state,
                loading: true,
            }

        case 'data':
            return {
                ...state,
                data: action.data,
                error: null,
                loading: false,
            }

        case 'error':
            return {
                ...state,
                error: 'Error fetching data. Try again',
                loading: false,
            }

        default:
            return state;
    }

}

function useFetch (url: string) {
    const [state, dispatch] = React.useReducer(
        fetchReducer,
        { data: null, error: null, loading: true }
    )

    React.useEffect(() => {
        dispatch({ type: 'fetch' })

        fetch(url, {
            headers: {
                accept: "application/json"
            }
        })
            .then((res) => res.json())
            .then((data) => dispatch({ type: 'data', data }))
            .catch((e) => {
                console.warn(e.message)
                dispatch({ type: 'error' })
            })
    }, [url])

    return {
        loading: state.loading,
        data: state.data,
        error: state.error
    }
}

export default function App() {
    const { loading, data, error } = useFetch(JOKE_URL);
    console.log(data);
    if (loading === true) {
        return <p>Loading</p>
    }
    if (error) {
        return (
            <React.Fragment>
                <p>{error}</p>
            </React.Fragment>
        )
    }
    return (
        <div>
            <h1>{data.joke}</h1>
        </div>
    );
}

我收到一些错误,例如: -> 类型的参数 '(state: { data: null; error: null; loading: boolean; }, action: ACTIONTYPE) => { data: null;错误:空;加载:布尔值; } | { 数据:对象;错误:空;加载:布尔值; } | { 错误:字符串;加载:布尔值;数据:空; }' 不可分配给 'ReducerWithoutAction' 类型的参数。 TS2769 -> 预期 0 个参数,但得到 1 个。TS2554

您应该为您的减速器设置 return 类型并且一切正常,我也确实更改了您的一些状态和类型以清理您的代码:

import * as React from "react";

const JOKE_URL = "https://icanhazdadjoke.com/";

const initialState = { loading: true };

type initState ={
  data?: any,
  error?: string,
  loading: boolean
}
type ACTIONTYPE =
    | { type: "fetch" }
    | { type: "data"; data: object }
    | { type: "error"};

function fetchReducer(state: initState, action: ACTIONTYPE):initState {
    switch (action.type) {
        case 'fetch':
            return {
                ...state,
                loading: true,
            }

        case 'data':
            return {
                ...state,
                data: action.data,
                loading: false,
            }

        case 'error':
            return {
                ...state,
                error: 'Error fetching data. Try again',
                loading: false,
            }

        default:
            return state;
    }

}

function useFetch (url: string) {
    const [state, dispatch] = React.useReducer(
        fetchReducer,
        initialState
    )

    React.useEffect(() => {
        dispatch({ type: 'fetch' })

        fetch(url, {
            headers: {
                accept: "application/json"
            }
        })
            .then((res) => res.json())
            .then((data) => dispatch({ type: 'data', data }))
            .catch((e) => {
                console.warn(e.message)
                dispatch({ type: 'error' })
            })
    }, [url])

    return {
        loading: state.loading,
        data: state.data,
        error: state.error
    }
}

export default function App() {
    const { loading, data, error } = useFetch(JOKE_URL);
    console.log(data);
    if (loading) {
        return <p>Loading</p>
    }
    if (error) {
        return (
            <React.Fragment>
                <p>{error}</p>
            </React.Fragment>
        )
    }
    return (
        <div>
            <h1>{data.joke}</h1>
        </div>
    );
}