【问题标题】:How can I properly define a type interface when using React useContext?使用 React useContext 时如何正确定义类型接口?
【发布时间】:2020-05-13 13:16:23
【问题描述】:

我有:

export interface AppStateType {
    isOnline: boolean
}

const AppContext = createContext([{}, () => { }]);

const AppProvider = (props) => {
    const [appState, setAppState] = useState<AppStateType>({
        isOnline: true
    })

    return <AppContext.Provider value={[appState, setAppState]}>
        {props.children}
    </AppContext.Provider>
}
export { AppContext, AppProvider }

当我尝试使用它时:

const [appState, setAppState] = useContext<AppStateType>(AppContext)

我收到一个 Typescript 错误:

Argument of type 'Context<{}[]>' is not assignable to parameter of type 'Context<AppStateType>'.
  The types of 'Provider.propTypes.value' are incompatible between these types.
    Type 'Validator<{}[]>' is not assignable to type 'Validator<AppStateType>'.
      Type '{}[]' is not assignable to type 'AppStateType'.

【问题讨论】:

  • This answer 可能会对您有所帮助 - 这是同一个星座。

标签: reactjs typescript react-hooks use-context


【解决方案1】:

您收到此错误的原因是因为 Context 的返回类型不是AppStateType,而是一个包含两个值的数组。 首先是 AppState其次是调度程序

使用打字稿,您可以在创建上下文时键入上下文

const AppContext = createContext<[AppStateType, React.Dispatch<any>]>(null);

发布这个,你可以像使用它一样简单地使用它

const [appState, setAppState] = useContext(AppContext);

Sample Demo

注意: 将 createContext 的默认值定义为 null,因为它仅在层次结构树中没有提供程序时使用。在这种情况下,它主要可能是一个错误

【讨论】:

  • 它会抛出什么错误,因为如果我创建像 const AppContext = createContext&lt;[AppStateType, React.Dispatch&lt;any&gt;]&gt;(null); 这样的上下文,它对我来说编译得很好。确保将 null 作为参数传递给 createContext,因为只有在没有可用的 PROvider 时才会使用它层次结构,这意味着您的代码不正确,因此最好抛出错误而不是被忽视
  • 是的,传递 null 而不是 [] 是一种选择。但这取决于环境 - 只有在 strict 模式/strictNullChecks 选项禁用的情况下才有可能,沙盒中就是这种情况(您可以尝试将 "strictNullChecks": true 添加到 tsconfig.json)。
  • 嗯,即使我在 TS 配置中添加 strictNullChecks 仍然有效
  • Here 是您的沙箱的副本,这些检查在其中被激活。
【解决方案2】:

createContext 的参数是上下文的默认值见here 因此,如果您的上下文类型是状态并像这样设置状态

[AppStateType,React.Dispatch<React.SetStateAction<AppStateType>>]

你需要给一个默认值

const AppContext = createContext([{}, () => { }]);

应该是

const AppContext = createContext<[AppStateType,React.Dispatch<React.SetStateAction<AppStateType>>]>([{isOnline:false},()=> false]);

【讨论】:

  • 那我不能设置appState
  • @Shamoon 你说得对,我更新了我的答案,将 State 和 sSetState 数组作为上下文类型,允许数组作为值传递
猜你喜欢
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
  • 1970-01-01
  • 2016-08-17
  • 2022-08-24
  • 1970-01-01
  • 2018-01-20
  • 1970-01-01
相关资源
最近更新 更多