React 路由器重定向条件

jai*_*fps 6 conditional-statements reactjs react-router

我正在尝试制作一个按钮,仅在验证正确完成后将用户重定向到新页面。

有没有办法做这样的事情?如何在类方法内激活路由?

import validator from './validator';

class Example {

  constructor(props) {
    super(props)
    this.saveAndContinue = thos.saveAndContinue.bind(this)
  }

  saveAndContinue () {
    var valid = validator.validate(this.props.form)
    if (valid) {
      axios.post('/path')
      <Redirect to='/other_tab'>
    } else {
      validator.showErrors()
    }
  }

  render() {
    <button onClick={this.saveAndContinue}>Save and Continue</button>
  }

}
Run Code Online (Sandbox Code Playgroud)

Pur*_*ory 6

正如所讨论的,您应该可以通过此处描述的方式访问该history对象。this.props.history

如果您查看该push功能,这会将您重定向到您需要的任何路线。例如:

// Use push, replace, and go to navigate around.
this.props.history.push('/home', { some: 'state' })
Run Code Online (Sandbox Code Playgroud)

https://reacttraining.com/react-router/web/api/history