react-router v4:以编程方式触发重定向(无需呈现 <Redirect / >)

react-router v4: triggering a redirect programmatically (without having to render a <Redirect / >)

我目前正在切换我的网络应用程序以做出反应。旧的位于 here.

我想做的是:当用户在文本字段中输入玩家的用户名并提交时,应用程序将重定向到相应的路由(/:username),并且文本字段被清除.

在反应版本中,这是我目前正在做的: https://github.com/AVAVT/g0tstats-react/blob/master/src/components/SideBar/SearchBox.js

submit(event){
    ...

    this.setState({
      redirect : true
    });

    ...
}

render(){
    ...
    {
          this.state.redirect && (
          <Redirect to={`/${this.state.username}`} push />
          )
    }
}

还挺管用的。但有两点我不喜欢它:

  1. 我正在渲染一个元素以便重定向。感觉很蠢很迂回。它散发着未来潜在错误的味道。
  2. 我对未清除的文本字段感到困惑。因为如果我将 state.username 设置为 null,<Redirect /> 组件将无法正确重定向。事实上,我无法精确控制重定向何时发生(除非我以另一种迂回方式进行)。

我已经搜索过替代方案,但找不到。 withRouter 不起作用,因为 <SearchBox /> 不是 <Route /> 并且没有收到历史道具。

那么我怎么能在 react-router v4 中说 "redirect me to that place NOW" 呢?

这是一个示例,显示了在使用 withRouter HOC 时,路由道具被注入到组件中,即使它们没有被路由到。

这是我的 App.js

    class App extends Component {
      render() {
        return (
          <div className="App">
            <BrowserRouter>
              <div>
                <Route path='/test' component={Sample} />
                <Sibling />
              </div>
            </BrowserRouter >
          </div>
        );
      }
    }

export default App;

这是我的Sample.js。这就像一个正在渲染子容器的示例容器。

export default class Sample extends React.Component {
    render() {
        return (
            <div>
                <span>{this.props.location.pathname}</span>
                <br />
                <Nested />
            </div>
        )
    }
}

即使没有 withRouter HOC,此组件也可以显示有关当前路由的信息,因为它被路由到。

这是我的 Nested.js.

class Nested extends React.Component {
    render() {
        return (
            <div>
                <span>I am nested {this.props.location.pathname}</span>
            </div>
        )
    }
}

export default withRouter(Nested);

我的嵌套组件需要 withRouter HOC 才能显示当前路由。

终于来了我的 Sibling.js。 (这就像您的示例,其中 <SearchBox /> 是兄弟姐妹。)

class Sibling extends React.Component {
    render() {
        return (
            <span>{this.props.location.pathname}</span>
        )
    }
}

export default withRouter(Sibling);

这里所需要的只是确保兄弟嵌套在路由器中,正如您在我的 App.js 中看到的那样,然后使用 withRouter HOC 它可以显示当前路径名.

澄清一下:如果组件可以访问当前路径名,那么它也可以通过执行此操作以编程方式更改路由。 this.props.history.push(some path)

希望对您有所帮助。