【问题标题】:How can I pass function using props in React Router Link?如何在 React Router Link 中使用道具传递函数?
【发布时间】:2021-04-01 20:52:48
【问题描述】:

我必须使用 Link 将函数传递给另一个组件

    testFavorite=()=>{
        console.log("work")
    }

    <Link 
       to={{
       pathname: '/popular',
         state:{
            testFavorite: this.testFavorite
         }
       }}>
   Popular</Link>

这就是我调用函数的方式 this.props.location.state.testFavorite();

这给了我这个错误

DataCloneError: 无法在“历史”上执行“pushState”:() => 无法克隆 testFavorite()。

【问题讨论】:

  • 此代码不足以澄清问题。您需要提供更多信息,可能是您如何为流行路径声明 &lt;Route&gt;,它是组件。您可以考虑添加一个带有重现错误的沙箱。
  • 你可以在这里找到代码codesandbox.io/s/…
  • 此外,下面是重点问题 function loadUser(){ console.log("load")} 执行后给我一个错误
  • 好像状态被序列化了,函数无法序列化:related question
  • 嘿@UmarJaved,你得到这个解决方案了吗?我有同样的问题。请分享解决方案。

标签: reactjs react-router react-router-v4 react-props


【解决方案1】:

&lt;Link /&gt; 组件中,我将“state”属性替换为“data”属性。现在可以使用了!

<Link 
    to={{
       pathname: '/popular',
       data:{
          testFavorite: this.testFavorite
       }
    }}
>
   Popular
</Link>

可以通过以下方式访问:this.props.history.location.data

【讨论】:

  • 您在哪里找到了这个解决方案?它甚至不在文档中,stackoverflow
  • 是的,文档不完整。我只尝试看看如果我使用“数据”属性会发生什么,因为我已经在路由中看到过,我们使用“数据”属性将数据传递给路由。
  • @Ali Amini 似乎无法重新加载页面。请帮助我遇到同样的问题。我需要从链接 传递一个函数,并希望将其调用到另一个页面中,例如 this.props.location.state.myFunction .
猜你喜欢
  • 2018-04-27
  • 2015-07-18
  • 2021-07-31
  • 2021-02-24
  • 2018-08-03
  • 2018-05-03
  • 2018-11-20
  • 2020-11-26
  • 2021-09-08
相关资源
最近更新 更多