Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

reactjs - Context Provider in TypeScript

I got the simplest context provider working on ES6 but I am unable to transform it for use on a TypeScript project. Every website I search for has a completely different take on implementing context api.

It is just a boolean variable and a function to set it, I keep running into problems with TypeScript.

Do I need to change the entire approach to make it work on TypeScript?

context.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)

reducer.js

export default (state, action) => {
  switch (action.type) {
    case 'set_load':
      return {
        load: action.load
      }
    default:
      return state
  }
}
question from:https://stackoverflow.com/questions/65889422/context-provider-in-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Generally you would want to type your context, eg.:

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

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

So when using either the provider or the consumer of LoadContext the types are known.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...