【发布时间】:2019-09-09 12:30:00
【问题描述】:
我正在尝试学习如何在 React 中使用钩子和上下文,但需要使用 TypeScript(也是新手)。
我的用例是授权:用户要么登录要么未登录,并且具有角色(例如“管理员”、“超级管理员”)。根据他们的授权状态,导航栏的呈现方式会有所不同。
除其他外,我正在尝试遵循 this 示例,简化为我的需求。
到目前为止,这是我的上下文和提供者:
import React, { createContext, useContext, Context, FC SetStateAction, useState } from 'react';
export interface IAuth {
loggedIn: boolean,
role: string
}
export const AuthContext = React.createContext<IAuth>({
loggedIn: false,
role: ''
});
const AuthProvider: FC = ({children}) => {
const [auth, setAuth] = useState({
loggedIn: false,
role: ''
});
return (
<AuthContext.Provider value={/*What to set as value?*/}>
{children}
</AuthContext.Provider>
)
}
export default AuthProvider;
然后是我的 NavBar,它使用了上下文的 Consumer:
class Nav extends React.Component {
render() {
return (
<AuthContext.Consumer>
{context => (
< div >
.. stuff ...
</div>
<ul className="nav">
{context.loggedIn ? (
<Fragment> .. links .. </Fragment>
) : (<Fragment> .. links .. </Fragment>
)}
</ul>
</div>
)
}
</AuthContext.Consumer>
)
}
} export default Nav;
如果我将 Provider 的值设置为这样,所有这些都可以正常工作:
<AuthContext.Provider value={{
loggedIn: false,
role: 'someRole'
}}>
但是,我还想提供setAuth 函数,以便从登录组件等更改这些值。
使用以下内容会给我错误:
<EmailContext.Provider value={[state, setState]}>
即Type '({ loggedIn: boolean; role: string; } | Dispatch<SetStateAction<{ loggedIn: boolean; role: string; }>>)[]' is missing the following properties from type 'IAuth': loggedIn, role
使用以下也会给我错误:
<AuthContext.Provider value={{data: auth,
updateAuth: () => { setAuth({... auth, loggedIn: true})}
}}>
data: auth 上的错误:Type '{ data: { loggedIn: boolean; role: string; }; updateAuth: () => void; }' is not assignable to type 'IAuth'.
Object literal may only specify known properties, and 'data' does not exist in type 'IAuth'.
我尝试过的各种其他事情也出现了类似的错误。
这些都是 Typescript 错误。如何以 Typescript 兼容的方式设置我的 Provider 值 - 并包括 set 操作而不仅仅是值?
【问题讨论】:
标签: reactjs typescript react-hooks react-context