【问题标题】:history definition missing in ReactNodeReactNode 中缺少历史定义
【发布时间】:2021-01-06 19:18:24
【问题描述】:

我编写了一个Login 组件,其中包含必须访问组件的history 对象的钩子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 类型,我得到:

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

此错误发生在这一行:

props.history.push('/');

我该如何解决这个问题?

【问题讨论】:

    标签: reactjs typescript react-router


    【解决方案1】:

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

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

    useHistory 挂钩可让您访问可用于导航的历史实例。

    您可以将其导入为:

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

    所以尝试如下:

    export default (props: { children: React.ReactNode }) => {
       const history = useHistory()
    
       // rest of the code
    }
    

    然后在没有props 的情况下使用:

    history.push('/');
    

    【讨论】:

    • 谢谢!所以你确认 Component 中没有包含历史的接口?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 2023-01-07
    • 2013-03-15
    • 2015-02-05
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    相关资源
    最近更新 更多