bra*_*rar 9 typescript reactjs use-context
我想以正确的方式定义接口,但我遇到了麻烦,因为即使参数为空,它也期待一个参数。
我正在使用useContext并且我定义了这样的接口:
//react-auth0-spa.tsx
interface Auth0Context {
......
loginWithRedirect: () => void; //I know this is the problem but I don't know what to define.
......
}
Run Code Online (Sandbox Code Playgroud)
在提供者中,value是:
//react-auth0-spa.tsx
<Auth0Context.Provider
value=({
....
loginWithRedirect: (...p: string[]) => auth0Client.loginWithRedirect(...p)
....
})
>
Run Code Online (Sandbox Code Playgroud)
现在,我import将上下文放到另一个文件中,如下所示:
const { isAuthenticated, loginWithRedirect, logout } = useAuth0()
这就是错误发生的地方
///components/NavBar.tsx
const { isAuthenticated, loginWithRedirect, logout } = useAuth0()
<div>
{!isAuthenticated && (
<button onClick={() => loginWithRedirect({})}>Log in</button> //Expected 0 arguments, but got 1
)}
</div>
Run Code Online (Sandbox Code Playgroud)
所以问题是loginWithRedirect需要 1 个参数,但它() => loginWithRedirect({})是一个空对象。这个问题可以通过any在接口内部使用来解决,但是如果我想明确定义它应该放什么?
我试过了,loginWithRedirect: ({}) => void但现在loginWithRedirect: (...p: string[]) => auth0Client.loginWithRedirect(...p)给了我这样的错误Type '{}' is not assignable to type 'string'.ts(2322)
没有打字稿的源代码是https://github.com/auth0-samples/auth0-react-samples/tree/master/01-Login/src
请帮忙。
Zai*_*een 11
首先的问题是:
您在界面中提供了这样一个函数的签名:
loginWithRedirect: () => void;
这意味着没有参数,无论何时定义该函数,您都将遵守此签名,但相反,您在给函数定义的同时将参数传递给该函数。
解决方案
为什么不这样做呢?
//react-auth0-spa.tsx
interface Auth0Context {
......
loginWithRedirect: (p: object) => void;
......
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22777 次 |
| 最近记录: |