首页 > 解决方案 > TypeScript 中的上下文提供程序

问题描述

我得到了最简单的 ES6 上下文提供程序,但我无法将其转换为用于 TypeScript 项目。我搜索的每个网站对实现上下文 API 都有完全不同的看法。

它只是一个布尔变量和一个设置它的函数,我一直遇到 TypeScript 的问题。

我是否需要更改整个方法以使其适用于 TypeScript?

上下文.js

import React from 'react'
import Reducer from './reducer'

export const LoadContext = React.createContext()

export const LoadProvider = ({ children }) => {
  const [state, dispatch] = React.useReducer(Reducer, {
    load: true
  })

  const setLoad = (load) => dispatch({ type: 'set_load', load })

  return (
    <LoadContext.Provider value={{ load: state.load, setLoad }}>
      {children}
    </LoadContext.Provider>
  )
}

export const useLoadContext = () => React.useContext(LoadContext)

减速器.js

export default (state, action) => {
  switch (action.type) {
    case 'set_load':
      return {
        load: action.load
      }
    default:
      return state
  }
}

标签: reactjstypescriptreact-context

解决方案


通常你会想要输入你的上下文,例如:

type LoadContextType = {
  load: any // Not sure what these are, type it appropriately
  setLoad: any
}

const context LoadContext = React.CreateContext<LoadContextType>(null)

因此,当使用LoadContext类型的提供者或消费者时是已知的。


推荐阅读