2017-06-13 20 views
1

我目前正在切換我的web應用程序以作出反應。舊的位於herereact-router v4:以編程方式觸發重定向(無需呈現<Redirect/>)

我想要做的是:當用戶輸入玩家的用戶名到文本字段並提交時,應用程序將重定向到相應的路線(/: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中說「重定向我到那個地方」呢?

+0

那麼從渲染你的''的組件發送路由道具怎麼樣?據推測,如果它沒有得到道具,因爲它沒有被直接路由到,那麼它的父母應該被路由到。 –

+0

'this.context.transitionTo(...)'是你如何編程重定向,如果我正確地閱讀你的問題。 – 1252748

+0

@promisified實際上,不,SearchBox的側邊欄內,這是' s'' – AVAVT

回答

2

下面是一個示例,顯示何時使用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)

我希望這會有所幫助。

+0

謝謝,爲我澄清了很多! – AVAVT

+0

太好了。樂於幫助! –

+0

授予我不是browserrouter專家,但我無法使'this.context.transitionTo'工作。很多'this.context.router是未定義的'。這是以編程方式切換頁面的新方法,並且不推薦使用「transitionTo」。進入是一個小光... – 1252748