【问题标题】:React Router v4 - Cannot pass state as prop via <Link>React Router v4 - 无法通过 <Link> 将状态作为道具传递
【发布时间】:2018-02-28 17:39:44
【问题描述】:

尝试在 Web 上使用 React Router v4 将状态从组件 A 作为道具传递给组件 B。以下代码返回此错误:“TypeError:无法读取未定义的属性“状态”。”为简洁起见,我删除了所有组件创建行:

// Component A

state = {
    selectedCountry: 'Gambia',
}

console.log(this.state.selectedCountry) // returns Gambia

// this is where it fails to pass state
<Link to={{ 
    pathname: '/component-b', // correct path
    state: { selectedCountry: this.state.selectedCountry }
}}>
    <button className="button">Button</button>
</Link>



// Component B

componentWillMount() {

// not received, sadly undefined
console.log(this.props.location.state.selectedCountry)

}

我在这里缺少什么?非常感谢!

编辑 1: 尝试建议在外部初始化 prop,但收到相同的未定义错误

// Component A
const selectedCountryProp = {
            pathname: '/trip-cards-container',
            state: { selectedCountry: this.state.selectedCountry }
        } 

return (
    <Link to={ selectedCountryProp }/>  
    {console.log(selectedCountryProp.state.selectedCountry)} 
    // logs expected Gambia
       <button className="button">Button</button>
    </Link>
    )

// Component B
componentWillMount() {
    console.log(this.props.location.state.selectedCountry)
    // logs cannot receive property of state of undefined
    // also tried with this.props.location.selectedCountryProp...
    // but logs cannot receive property of selectedCountryProp of
    // undefined
}

【问题讨论】:

  • 如果您尝试console.log('this.props'),您会看到什么?
  • 如果我这样做,我会得到this.props,但如果我将其设置为console.log(this.props),我会得到[object Object]
  • 我认为this 指的不是正确的上下文。尝试在 Link 之外初始化对象 -> const linkProp = { ... } &lt;Link to={ linkProp } /&gt;
  • @ReiDien 感谢您的建议!我试了一下,但仍然收到未定义的错误 - 我认为这可能与通过 this.props.location.state.selectedCountry 接收道具的方式有关。我将附加我在上面尝试过的内容
  • 我也遇到了同样的问题!网上找不到解决办法!!您发现任何有用的技巧了吗??

标签: reactjs react-router


【解决方案1】:

也许您正在单独加载组件 B?例如刷新相同的路线。如果您从 A 导航,则每次都必须从 A 导航到 B。

【讨论】:

    猜你喜欢
    • 2018-01-29
    • 2018-01-17
    • 2019-08-09
    • 2018-08-03
    • 2015-07-18
    • 2018-12-17
    • 2018-08-28
    • 2018-07-03
    • 2018-02-20
    相关资源
    最近更新 更多