通过链接传递值的问题,单击后会生成值

时间:2019-04-06 20:56:41

标签: reactjs

我正在尝试通过链接中的页面传递价值。但是,问题是该值是在单击后生成的。因此,我在下一页中获得的值始终为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。

1 个答案:

答案 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>