我正在尝试通过链接中的页面传递价值。但是,问题是该值是在单击后生成的。因此,我在下一页中获得的值始终为null。这是我的代码:
Go(){
somefunction()
.then(result => {this.setState({value: valueGeneratedBysomefunction})})
}
<Link to={{ pathname: '/nextpage', state: { value: this.state.value}}}>
<Button size="sm" color="primary" onClick={this.Go.bind(this)}>Go!</Button>
</Link>
然后我通过
调用下一页中的值console.log(props.location.state)
结果是:
value: ""
我在想,也许我可以以编程方式重定向到另一页并在.then()
中执行重定向。但是,我尝试了history.push()
,this.context.router.push()
。它们都不起作用。我的react-router版本是^ 3.2.0。
答案 0 :(得分:0)
由于state
是异步的,因此您应该使用新的setState
进行的操作应该在setState
回调中完成。
Go() {
somefunction()
.then(result => {
this.setState({
value: valueGeneratedBysomefunction
}, () => {
// do the redirect here and you have access to the new state through this.state
this.context.router.push({
pathname: '/nextpage',
state: { value: this.state.value }
})
})
})
}
<Button size="sm" color="primary" onClick={this.Go.bind(this)}>Go!</Button>