【问题标题】:React useHistory, Object is of type 'unknown'React useHistory,对象的类型为“未知”
【发布时间】:2021-07-13 20:35:24
【问题描述】:

我在使用 react hook useHisotry 时遇到错误Object is of type 'unknown',这是详细信息,提前感谢您的帮助!

节点版本:v12.14.1

反应版本:17.0.1

react-router-dom 版本:16.9.8

@types of react-router-dome 版本:^5.1.6

import { useHistory } from "react-router-dom";
const history = useHistory();

useEffect(() => {
    if (history.location.state) {
      const taskId: any = history.location.state.taskId
      getItemList(taskId)
    }
  }, [])

// 错误信息

  Object is of type 'unknown'.  TS2571

    252 |   useEffect(() => {
    253 |     if (history.location.state) {
  > 254 |       const taskId: any = history.location.state.taskId
        |                           ^
    257 |     }

【问题讨论】:

  • 为什么要这样声明常量const taskId: any = history.location.state.taskId
  • 请只尝试这样const taskId=history.location.taskId
  • @EtsukoSusui 你确定吗?你知道那里有什么吗?
  • 您是否在组件实现之外使用历史记录?
  • @lissettdm,不,我在函数组件中使用它。

标签: reactjs react-router react-hooks react-router-dom


【解决方案1】:

我试图做一些类似的事情来获取当前组件导航到的上一个 URL。

这是我所做的:

在你推送历史对象中的url的组件中:

 history.push(`/overview`, {
      from: '/map',
    } as { from: string });

现在,在您要使用历史对象的组件中:

const history = useHistory();
const state = history.location.state as { from: string }

console.log(state.from); // this will give you the value from the state

在您的情况下,将“from”替换为“taskId”。

我希望这会有所帮助。由于您定义了要包含在位置状态中的属性,因此为它定义类型是安全的。

【讨论】:

    【解决方案2】:

    您应该考虑从 props 获取历史记录。 https://reactrouter.com/web/api/history/history-is-mutable 请参阅下面的示例。

    export default function ExampleComponent(props: any) {
    
    const { taskId } = props.history.location.state;
    
     console.log(taskId);
    
    }
    
    

    如果您不想使用道具,请考虑使用 useLocation hook 。 useLocation 挂钩返回代表当前 URL 的位置对象。你可以把它想象成一个 useState,只要 URL 发生变化,它就会返回一个新的位置。 https://reactrouter.com/web/api/Hooks/uselocation

    
    import {useLocation} from "react-router-dom";
    export default function ExampleComponent(props: any) {
     let location = useLocation();
    const { taskId } = location.state;
    
      console.log(taskId);
    
    }
    

    【讨论】:

    • 他们正在尝试使用useHistory,所以历史不会来自道具。
    • @Xymotech 历史是可变的 历史对象是可变的。因此建议从 的 render props 访问位置,而不是从 history.location。这可以确保您对 React 的假设在生命周期钩子中是正确的,请参阅 reactrouter.com/web/api/history/history-is-mutable
    猜你喜欢
    • 2020-08-23
    • 2022-01-21
    • 2021-06-19
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 2022-01-25
    相关资源
    最近更新 更多