【问题标题】:Property 'XXXX' does not exist on type 'unknown'类型“未知”上不存在属性“XXXX”
【发布时间】:2021-06-30 07:31:00
【问题描述】:

我有一个组件,我使用useHistory 在单击按钮时移动到另一个组件。这是到目前为止的代码:

Component1.tsx

 let history = useHistory();

 const someEventHandler = event => {
    history.push({
        pathname: '/Comp2',
        search: '?flow=abc',
        state: { detail: 'some_value' }
    });
 };

...
<Button onClick={someEventHandler}>Submit</Button>

Component2.tsx

const location = useLocation();
useEffect(
    () => {
        console.log(location.pathname);
        console.log((location.state).detail); <-- Error here
    }
)

按钮正在使用正确的路径和 queryParams 进行重定向。但我无法获得从第一个组件发送的详细信息部分。

我收到以下错误:

any
Property 'details' does not exist on type 'unknown'.ts(2339)

我正确发送了道具,但仍然无法从useLocation 接收数据(详细信息)部分。我们能以某种方式得到这个吗?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    来自docs

    history.push({
      pathname: '/home',
      search: '?the=query'
    }, {
      some: state
    });
    

    您需要在单独的对象中定义状态

    此外,当与打字稿一起使用时,您需要告诉它您的状态可能是什么样子,例如

    const location = useLocation<{ details: string | undefined }>()
    

    否则你会得到一个打字稿编译错误

    【讨论】:

    • 我已经从文档中尝试过这种方法:history.push('/home?the=query', { some: 'state' }); 但仍然遇到同样的错误。
    • @SharathKamlekar 查看我的更新答案。您可能会收到打字稿错误,但为了将来参考,您确实应该提及打字稿的用法以及错误来自控制台还是编译过程中的终端
    猜你喜欢
    • 2020-02-24
    • 2017-08-21
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 2020-03-31
    • 2020-09-02
    • 2021-01-09
    • 1970-01-01
    相关资源
    最近更新 更多