首页 > 解决方案 > 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。

标签: reactjs

解决方案


你想做的事情应该使用 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>

推荐阅读