使用 useContext、ureReducer 和 useMemo 做出反应:XXX 缺少 YYY 类型的以下属性 TS2739 错误

时间:2021-06-08 06:19:28

标签: reactjs use-context

我不是 React 专家,所以在这里提问。 我想用 React.useContext API 创建应用程序上下文。 这是我的简单示例代码:

import {
    createContext,
    FC,
    useCallback,
    useContext,
    useMemo,
    useReducer,
} from 'react'

type State = {
    modal: boolean,
    errorMessage: string | null,
}

type Action =
  | { type: 'TOGGLE_MODAL'}
  | { type: 'SET_ERROR'}

const initialState: State = {
    modal: false,
    errorMessage: null,
}

export const ApplicationContext = createContext(initialState)

export const useApplicationContext = () => {
    return useContext(ApplicationContext)
}

export const reducer = (state: State, { type, payload }) => {
  switch (type) {
    case 'TOGGLE_MODAL':
      const { modal } = payload
      return {
        ...state,
        modal,
      }
    case 'SET_ERROR':
      const { errorMessage } = payload
      return {
        ...state,
        errorMessage,
      }
    default: {
      throw Error(
        `Unexpected action type in ApplicationContext reducer: '${type}'.`
      )
    }
  }
}

const ApplicationContextProvider: FC = (props) => {
  const [state, dispatch] = useReducer(reducer, initialState)

  const toggleModal = useCallback((target) => {
    dispatch({ type: 'TOGGLE_MODAL', payload: { modal: target }})
  }, [])

  const setError = useCallback((message) => {
    dispatch({ type: 'SET_ERROR', payload: { errorMessage: message } })
  }, [])

  const value = useMemo(
    () => ({
      state,
      toggleModal,
      setError,
    }),
    [setError, state, toggleModal]
  )

  return (
    <ApplicationContext.Provider value={value}>
      {props.children}
    </ApplicationContext.Provider>
  )
}

export default ApplicationContextProvider

但是,当我编译 src 时,出现如下错误:

Type '{ state: { modal: any; errorMessage: string | null; } | { errorMessage: any; modal: boolean; }; toggleModal: (target: any) => void; setError: (message: any) => void; }' is missing the following properties from type 'State': modal, errorMessage  TS2739

所以我试图理解这个错误试图说明什么,但完全不知道。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

错误所在的行也是相关的,但我还是可以找到它

Type '{ state: { modal: any; errorMessage: string | null; } | { errorMessage: any; modal: boolean; }; toggleModal: (target: any) => void; setError: (message: any) => void; }' is missing the following properties from type 'State': modal, errorMessage  TS2739

此错误的意思是您试图将具有属性 statetoggleModalsetError 的对象设置为 State 参数,该参数需要属性 { {1}} 和 modal。 Typescript 只是告诉您您正在尝试使用不正确的值,如果您尝试运行它,它将无法正常工作。

问题出在这里:

errorMessage

ApplicationContext 被初始化为一个值为 export const ApplicationContext = createContext(initialState) // ... const value = useMemo( () => ({ state, toggleModal, setError, }), [setError, state, toggleModal] ) return ( <ApplicationContext.Provider value={value}> {props.children} </ApplicationContext.Provider> ) 的 React.Context。但是,当您尝试设置该值时,您将其设置为 State{ state, toggleModal, setError } 不匹配的对象。

解决方案 - 要么传入 State,要么用 value={state} 初始化上下文