React Router 重定向条件

React Router Redirect Conditional

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

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

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>
  }

}

就像 Purgatory 说你可以不使用 <Redirect /> 那样做,但否则你可以让你的组件成为有状态组件,然后像这样进行条件渲染

render() {
    !this.state.redirect ? 
      <button onClick={this.saveAndContinue}>Save and Continue</button> :
      <Redirect to='/other_tab'>
  }

并让 saveAndContinue() 更改组件状态。

saveAndContinue () {
    var valid = validator.validate(this.props.form)
    if (valid) {
      axios.post('/path')
      this.setState({redirect: true});
    } else {
      validator.showErrors()
    }
  }

当状态改变时会导致重新渲染,这次 <Redirect /> 会被渲染。

注意:实际上我没有运行这个代码片段,所以它可能包含(希望是小的)错误。

如前所述,您应该可以通过 this.props.history 访问 history 对象,如 here 所述。

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

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

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