Álv*_*aro 5 typescript reactjs react-context
我在 ES6 上使用了最简单的上下文提供程序,但我无法将其转换为在 TypeScript 项目上使用。我搜索的每个网站在实现 context 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)
Run Code Online (Sandbox Code Playgroud)
减速器.js
export default (state, action) => {
switch (action.type) {
case 'set_load':
return {
load: action.load
}
default:
return state
}
}
Run Code Online (Sandbox Code Playgroud)
一般来说,您需要输入您的上下文,例如:
type LoadContextType = {
load: any // Not sure what these are, type it appropriately
setLoad: any
}
const context LoadContext = React.CreateContext<LoadContextType>(null)
Run Code Online (Sandbox Code Playgroud)
因此,当使用类型的提供者或消费者时,LoadContext类型是已知的。
| 归档时间: |
|
| 查看次数: |
4265 次 |
| 最近记录: |