2017-07-19 87 views
0

我正在使用一系列React,Flux和react-router(v4)。 我的目標是實現服務器端驗證,並根據驗證結果重定向到另一個路線或保持當前並顯示驗證消息。react-router:從組件或存儲更改路由

我的想法如下這樣的場景:

1)組件收集數據,並呼籲採取行動

2)商店獲取響應數據是否有效,不斷產生和發出的變化

3)組件檢測的變化並收集國家。如果驗證成功,則重定向到新的路由

的功能組件中的部分看起來像(寫在TS):

public componentWillUpdate(): void { 
    if (this.state.status === ValidationStatus.OK) { 
     this.context.router.history.push(/* another route */); 
    } 
} 

public render(): JSX.Element { 
    return (
     <div> 
      <div className='form-group'> 
       <input type='text' ref='Field1' /> 
       <input type='text' ref='Field2' /> 
      </div> 
      <span onClick={ (e) => this.tryToValidate(e) }>Go</span> 
     </div> 
    ); 
} 

public componentDidMount(): void { 
    this.onChange = this._onChange.bind(this); 
    MyStore.addChangeListener(this.onChange); 
} 

private _onChange() { 
    this.setState({ 
     status: MyStore.getStatus() 
    }); 
} 

但它不能正常工作 - 重定向被觸發僅在第二次點擊。

我該如何更改我的代碼才能使其工作?大概是從商店或其他東西調用重定向?...

P.S.路由器的歷史是組件包括這樣:

public static contextTypes = { 
    router: PropTypes.shape({ 
     history: PropTypes.shape({ 
      createHref: PropTypes.func.isRequired, 
      push: PropTypes.func.isRequired, 
      replace: PropTypes.func.isRequired 
     }).isRequired 
    }).isRequired 
} 

更新:

找到一個解決方案,它的工作原理,但看起來醜陋:

從組件回調
  • 通存儲作爲有效載荷(回調引發context.router.history.push(/* another route */);

  • 在商店中執行此回調如果發送r驗證是可以的。

回答

0

最後我找到了解決方案。這只是必要包括歷史存儲一樣(它只是草稿,不工作的代碼):

​​

唯一的缺點是,它與HashRouter工作只是不能與BrowserRouter。我不知道爲什麼,試圖找出...

相關問題