reactjs - ReactNode 中缺少历史定义
问题描述
我编写了一个组件,其中包含必须访问组件对象Login
的钩子:useEffect
history
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('/');
我该如何解决?
解决方案
根据您的功能组件,您可以使用useHistory()
钩子代替:
React Router 附带了一些钩子,可让您访问路由器的状态并从组件内部执行导航。
该
useHistory
钩子使您可以访问可用于导航的历史实例。
您可以将其导入为:
import { useHistory } from "react-router-dom";
所以尝试如下:
export default (props: { children: React.ReactNode }) => {
const history = useHistory()
// rest of the code
}
然后不使用props
as:
history.push('/');
推荐阅读
- ssl - HTTPS双向认证的客户端公钥是什么?
- python - 从 Flask 发布到 RabbitMQ
- excel - 如何翻译excel可以理解的日期/时间格式
- sql-server - 安装 SSDT VS 2015 17.3 和 17.4 时出错 - 系统找不到指定的文件
- react-native - Axios 获取响应未转移到状态 [Native React]
- java - java 8 中的流 collect() 中的参数如何理解
- c++ - (SFML 库)RenderWindow 构造函数抛出异常
- matlab - 如何在plot3中指定虚线?
- snowflake-cloud-data-platform - 雪花中的 LEVEL 等价物是多少
- spring - Apache Camel CXF 组件问题