如何在 React Router Link 中使用 props 传递函数?

问题描述

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

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

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

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

这是给我这个错误

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

解决方法

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

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

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