首页 > 解决方案 > ReactNode 中缺少历史定义

问题描述

我编写了一个组件,其中包含必须访问组件对象Login的钩子:useEffecthistory

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.ReactNodeprops组件的类型,我得到:

类型'{ children: ReactNode; 上不存在属性'history';}'

此错误发生在此行:

props.history.push('/');

我该如何解决?

标签: reactjstypescriptreact-router

解决方案


根据您的功能组件,您可以使用useHistory()钩子代替:

React Router 附带了一些钩子,可让您访问路由器的状态并从组件内部执行导航。

useHistory钩子使您可以访问可用于导航的历史实例。

您可以将其导入为:

import { useHistory } from "react-router-dom";

所以尝试如下:

export default (props: { children: React.ReactNode }) => {
   const history = useHistory()

   // rest of the code
}

然后不使用propsas:

history.push('/');

推荐阅读