【发布时间】: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 = { ... } <Link to={ linkProp } /> -
@ReiDien 感谢您的建议!我试了一下,但仍然收到未定义的错误 - 我认为这可能与通过
this.props.location.state.selectedCountry接收道具的方式有关。我将附加我在上面尝试过的内容 -
我也遇到了同样的问题!网上找不到解决办法!!您发现任何有用的技巧了吗??
标签: reactjs react-router