React Router v4 - 无法通过<link />将状态作为prop传递

时间:2017-09-19 20:00:57

标签: reactjs react-router

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

// 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:尝试在外面初始化道具的建议,但收到了未定义的相同错误

// 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
}

1 个答案:

答案 0 :(得分:0)

也许你是分别加载B组件?例如刷新相同的路线。如果您从A导航,则必须每次都从A导航到B.