gpt4 book ai didi

reactjs - 如何使我的 React 上下文提供程序类型安全

转载 作者:行者123 更新时间:2023-12-03 08:00:41 24 4
gpt4 key购买 nike

我有一个 React 上下文提供程序。我用JS写的,现在用TS重写。我很难让这些类型正常工作。上下文被初始化为未定义。稍后使用 action 属性(可以是任何 ActionCreator)和 args 属性(可以是任何 Action)进行设置>。我尝试了几种不同的方法,但就像打地鼠一样。这是我目前拥有的:

import { createContext, FC, PropsWithChildren, useState } from 'react'
import { Action, ActionCreator } from 'redux'
import { Dispatch, SetStateAction } from "react";

type ModalStateT = {
action: ActionCreator<any> | undefined
args: Action | undefined
}

type ModalContextT = {
modalState: ModalStateT
setModalState: Dispatch<SetStateAction<ModalStateT>>
resetModalState: ({action, args}: ModalStateT) => void
}

export const ModalContext = createContext<ModalContextT | undefined>(undefined)

const ModalProvider: FC<PropsWithChildren> = ({ children }) => {

const defaultState = {
action: undefined,
args: undefined,
}
const [modalState, setModalState] = useState(defaultState)

const resetModalState = () => {
setModalState(defaultState)
}
return (
<ModalContext.Provider value={{ modalState, setModalState, resetModalState }}>
{ children }
</ModalContext.Provider>
)
}

export default ModalProvider

我的 IDE 确实在此处显示错误 value={{ modalState, setModalState, resetModalState }}

这是我得到的错误:

TS2322: Type 'Dispatch<SetStateAction<{ action: undefined; args: undefined; }>>' is not assignable to type 'Dispatch<SetStateAction<ModalStateT>>'.
Type 'SetStateAction<ModalStateT>' is not assignable to type 'SetStateAction<{ action: undefined; args: undefined; }>'.
Type 'ModalStateT' is not assignable to type 'SetStateAction<{ action: undefined; args: undefined; }>'.
Type 'ModalStateT' is not assignable to type '{ action: undefined; args: undefined; }'. Types of property 'action' are incompatible.           
Type 'ActionCreator<any> | undefined' is not assignable to type 'undefined'.        
Type 'ActionCreator<any>' is not assignable to type 'undefined'.

我该如何解决这个问题?提前致谢!

最佳答案

注释您的defaultStateModalStateT类型:

const defaultState: ModalStateT = {
action: undefined,
args: undefined,
}

否则 TypeScript 将推断出更具限制性的类型。

这就是为什么它会给你这样的错误:

Type 'ActionCreator<any>' is not assignable to type 'undefined'.

这是 TypeScript 告诉你它推断出的类型为 undefined而不是限制较少的 ActionCreator<any> | undefined你想要的样子。

关于reactjs - 如何使我的 React 上下文提供程序类型安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74311348/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com