问题
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.
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>
)
}
回答1:
There's no way of avoiding declaring the interface and the runtime values, because TS's types disappear at runtime, so you're only left with the runtime values. You can't generate one from the other.
However if you know that you are only ever going to access the context within the TodoContextProvider
component you can avoid initialising TodoContext
by cheating a little bit and just telling TS that what you're passing it is fine.
const TodoContext = React.createContext<TodoContext>({} as TodoContext)
If you do always make sure to only access the context inside of TodoContextProvider
where todos
and setTodos
are created with useState
then you can safely skip initialising TodoContext
inside of createContext
because that initial value will never actually be accessed.
来源:https://stackoverflow.com/questions/61333188/react-typescript-avoid-context-default-value