这是我的上下文创建器,我在其中为上下文创建了初始状态,但我还必须传递我想在项目中通过useContext使用的函数。我以这种方式传递了函数。任何人都可以告诉我更好的方法吗?附言这种方法工作正常,但我认为它会给大项目带来问题
import { createContext } from "react"
import { initialState } from "./Initstate"
import { IInitState } from "./alert/IInitState"
export interface IGithubContext {
State: IInitState,
searchusers: (login: string) => void,
clearUsers: () => void,
getuser: (login: string) => void,
getuserrepos: (login: string) => void
}
const istate: IGithubContext = {
State: initialState,
clearUsers: () => null,
getuser: () => null,
getuserrepos: () => null,
searchusers: () => null
}
const GithubContext = createContext<IGithubContext>(istate)
export default GithubContext
这是我的提供程序,其中包含我尝试传入 value={{}} 的函数,如您所见
import GithubReducer, { Action } from "./GithubReducer"
import GithubContext from "./GithubContext"
import { SET_LOADING, CLEAR_USERS, USER_LOADING, GET_USER, SEARCH_USERS, GET_REPOS } from "./Types"
import { IInitState } from "./alert/IInitState"
import { initialState } from "./Initstate"
const GithubState = (props: any) => {
const [state, dispatch] = useReducer<React.Reducer<IInitState, Action>>(GithubReducer, initialState)
const searchusers = async (search: string) => {
setloading()
const data = await fetch(`https://api.github.com/search/users?q=${search}`)
const items = await data.json()
dispatch({ type: SEARCH_USERS, payload: items.items })
}
const getuser = async (login: string) => {
userloading()
const data = await fetch(`https://api.github.com/users/${login}`)
const items = await data.json()
dispatch({ type: GET_USER, payload: items })
}
const getuserrepos = async (login: string) => {
const data = await fetch(`https://api.github.com/users/${login}/repos?per_page=5&sort=created:asc`)
const items = await data.json()
dispatch({ type: GET_REPOS, payload: items })
}
const clearUsers = () => dispatch({ type: CLEAR_USERS })
const setloading = () => dispatch({ type: SET_LOADING })
const userloading = () => dispatch({ type: USER_LOADING })
return (
<GithubContext.Provider value={{
State: {
users: state.users,
user: state.user,
loading: state.loading,
userloading: state.userloading,
repos: state.repos,
alert: state.alert,
},
searchusers,
clearUsers,
getuser,
getuserrepos
}}>
{props.children}
</GithubContext.Provider>
)
}
export default GithubState
当Provider
未包含需要上下文的组件或组件尝试从上下文访问值而无法访问它时(不是Provider
的子项(时,上下文中函数的值将默认为提供的值。
例如,当某些组件调用函数getuser
并且无法访问上下文提供程序时,函数默认值的当前实现getuser: () => null
静默失败。所以是的,这会导致一些问题。
另一种方法是在函数的默认值中抛出错误,以便当不是Provider
子项的ComponentA
调用函数时getuser
或searchusers
,而不是静默失败,函数将抛出错误。使用这种方法,您至少会知道某些无法访问上下文的组件试图从中获取一些值。
const istate: IGithubContext = {
State: initialState,
clearUsers: () => { throw new Error('GithubContext not avaliable') },
getuser: () => { throw new Error('GithubContext not avaliable') },
/*other values*/
}