反应&TypeScript:避免上下文默认值 [英] React & TypeScript: Avoid context default value

查看:38
本文介绍了反应&TypeScript:避免上下文默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了更好地学习 React、TypeScript 和 Context/Hooks,我正在制作一个简单的 Todo 应用程序.但是,使上下文所需的代码感觉很麻烦.

In the effort to better learn React, TypeScript, and Context / Hooks, I'm making a simple Todo app. However, the code needed to make the context feels cumbersome.

例如,如果我想改变一个 Todo 有什么,我必须在三个地方改变它(ITodo 接口、默认上下文值、默认状态值).如果我想传递一些新的东西,我必须在三个地方(TodoContext、TodoContext 的默认值和 value=)这样做.有没有更好的方法不用写这么多代码?

For example, if I want to change what a Todo has, I have to change it in three places (ITodo interface, default context value, default state value). If I want to pass down something new, I have to do that in three places (TodoContext, TodoContext's default value, and value=). Is there a better way to not have to write so much code?

import React from 'react'

export interface ITodo {
    title: string,
    body?: string,
    id: number,
    completed: boolean
}

interface TodoContext {
    todos: ITodo[],
    setTodos: React.Dispatch<React.SetStateAction<ITodo[]>>
}

export const TodoContext = React.createContext<TodoContext>({
    todos: [{title: 'loading', body: 'loading', id: 0, completed: false}],
    setTodos: () => {}
})

export const TodoContextProvider: React.FC<{}> = (props) => {
    const [todos, setTodos] = React.useState<ITodo[]>([{title: 'loading', body: 'loading', id: 0, completed: false}])

    return (
        <TodoContext.Provider value={{todos, setTodos}}>
            {props.children}
        </TodoContext.Provider>
    )
}

推荐答案

一段时间后,我想我找到了解决这个问题的最佳方法.

After awhile, I think I've found the best way to go about this.

import React from 'react'

export interface ITodo {
    title: string,
    body?: string,
    id: number,
    completed: boolean
}

const useValue = () => {
    const [todos, setTodos] = React.useState<ITodo[]>([])

    return {
        todos,
        setTodos
    }
}

export const TodoContext = React.createContext({} as ReturnType<typeof useValue>)

export const TodoContextProvider: React.FC<{}> = (props) => {
    return (
        <TodoContext.Provider value={useValue()}>
            {props.children}
        </TodoContext.Provider>
    )
}

这样,在向您的上下文添加新内容时会发生单点变化,而不是最初的三点变化.享受!

This way, there is single point of change when adding something new to your context, rather than triple point of change originally. Enjoy!

这篇关于反应&amp;TypeScript:避免上下文默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆