[英]history definition missing in ReactNode
我寫了一個Login
組件,其中包含必須訪問組件history
object 的鈎子useEffect
:
export default (props: { children: React.ReactNode }) => {
const alertContext = useContext(AlertContext);
const authContext = useContext(AuthContext);
const { setAlert } = alertContext;
const { login, error, clearErrors, isAuthenticated } = authContext;
useEffect(() => {
if (isAuthenticated) {
props.history.push('/');
}
if (error === 'Invalid Credentials') {
setAlert(error, 'danger');
clearErrors();
}
// es-lint-disable-next-line
}, [error, isAuthenticated, props.history]);
即使我已經將React.ReactNode
定義為組件的props
類型,我仍然得到:
屬性 'history' 在類型 '{ children: ReactNode; 上不存在; }'
此錯誤發生在這一行:
props.history.push('/');
我該如何解決?
根據您的功能組件組件,您可以改用useHistory()
掛鈎:
React Router 附帶了一些鈎子,可讓您訪問路由器的 state 並從組件內部執行導航。
useHistory
掛鈎使您可以訪問可用於導航的歷史實例。
您可以將其導入為:
import { useHistory } from "react-router-dom";
所以嘗試如下:
export default (props: { children: React.ReactNode }) => {
const history = useHistory()
// rest of the code
}
然后在沒有props
的情況下使用:
history.push('/');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.