reactjs - 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
}
}
解决方案
通常你会想要输入你的上下文,例如:
type LoadContextType = {
load: any // Not sure what these are, type it appropriately
setLoad: any
}
const context LoadContext = React.CreateContext<LoadContextType>(null)
因此,当使用LoadContext
类型的提供者或消费者时是已知的。
推荐阅读
- azure - 如何使用应用程序洞察力进行分布式跟踪/跟踪
- android - 使用 Kotlin for Android Application 将图像编码为 Base64
- javascript - 使用 List JS 在 Angular JS 中进行过滤和排序
- mysql - 比较以 % 为单位的行值以衡量增长
- plugins - 问:如何使用插件:在具有多个内联 ckeditor 的页面上查找
- r - 给定 R 中的百分位等级,生成指数分布
- javascript - 如何使用 PHP foreach 生成用作插件变量的 javascript 对象数组?
- c# - 为什么我不能使用 iTextSharp 使用此代码将 PDF 附加到另一个 PDF?
- c++ - 以编程方式获取 Samba 共享卷 ID
- python - 如何按元素排序 python 列表?