reactjs - Link传值问题,点击后生成值
问题描述
我试图通过链接中的页面传递价值。但是,问题是,该值是点击后生成的。所以我在下一页得到的值总是空的。这是我的代码:
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()
。它们都不起作用。我的反应路由器版本是 ^3.2.0。
解决方案
你想做的事情应该使用 newstate
应该在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>
推荐阅读
- spatial - 多年数据的空间自相关
- android-studio - 如何解决 RangeError(index): Invalid value: Valid value range is empty: 1 in Flutter/Dart
- node.js - 多次写入时节点网络数据合并
- java - 如何转换 double x1 = input.nextDouble(); 成一个数组?
- vba - 如果该行出现在表格前面的页面上,则将表格前的行与表格一起移动
- c++ - 对“__imp_WSAStartup”的未定义引用
- typescript - 为什么 ts-toolbelt 库使用“O 扩展未知”表达式
- docker - Docker - ipv6(容器中的桥网关地址)如何在容器中获取客户端的 ip6 地址?
- forgerock - 通过 Forgerock AM 7.1 创建用户时出现错误代码 65
- sql - 如何从 Amazon Athena 中的其他表创建分区表?