简体   繁体   English

将 React useReducer 转换为 TypeScript

[英]Converting React useReducer to TypeScript

I am trying to convert a useReducer hooks to TypeScript, It's working fine as useReducer hooks, however not in TypeScript.我正在尝试将 useReducer 钩子转换为 TypeScript,它作为 useReducer 钩子工作正常,但在 TypeScript 中没有。

Here is my code,这是我的代码,

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

I am getting some errors like: -> Argument of type '(state: { data: null; error: null; loading: boolean; }, action: ACTIONTYPE) => { data: null; I am getting some errors like: -> Argument of type '(state: { data: null; error: null; loading: boolean; }, action: ACTIONTYPE) => { data: null; error: null;错误:null; loading: boolean;装载:boolean; } | } | { data: object; {数据:object; error: null;错误:null; loading: boolean;装载:boolean; } | } | { error: string; {错误:字符串; loading: boolean;装载:boolean; data: null;数据:null; }' is not assignable to parameter of type 'ReducerWithoutAction'. }' 不可分配给“ReducerWithoutAction”类型的参数。 TS2769 -> Expected 0 arguments, but got 1. TS2554 TS2769 -> 预期为 0 arguments,但得到 1。TS2554

You should set return type for your reducer and all working fine, also i did change some of your state and types for cleaning your code:你应该为你的减速器设置返回类型并且一切正常,我也改变了你的一些 state 和类型来清理你的代码:

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

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

相关问题 使用 useReducer + Typescript 反应 Conetxt - '没有与此调用匹配的重载' - React Conetxt with useReducer + Typescript - 'No overload matches this call' 如何为 useReducer 输入状态和分派 - 打字稿和反应 - how to type state and dispatch for useReducer - typescript and react 使用 React useContext 和 useReducer 时出现打字稿错误 - Typescript error when using React useContext and useReducer Typescript React UseReducer Type Error on Provider Value - Typescript React UseReducer Type Error on Provider Value React TypeScript:使用 useReducer 时出现 TS 错误 - React TypeScript: TS Error when using useReducer React-TypeScript:预期 0 个参数,但在 useReducer 上得到 1 个 - React-TypeScript: Expected 0 arguments, but got 1 on a useReducer React:TypeScript:使用 useReducer 设置和获取全局上下文 - React: TypeScript: Set and Get Global Context with useReducer 将 Redux 转换为 React Context API + useReducer - Converting Redux to React Context API + useReducer React w/Typescript: useReducer, Action Interface w/ Union Type - React w/Typescript: useReducer, Action Interface w/ Union Type 有人可以解释我使用 useReducer 和 TypeScript 实现 React 调度的这一行吗? - Can someone explain this line of my implementation of React dispatch with useReducer and TypeScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM