2017-06-15 36 views

回答

1

nextState由路由器基礎結構提供,包含有關路線,參數和您要去的位置的信息。這使您可以根據此信息加載組件,或傳遞自定義屬性或對此信息執行任何您想要的操作。

簡單的例子只是爲了演示

const { Router, Route, Link, hashHistory, Redirect } = ReactRouter 
 

 
const App = props => (
 
    <div> 
 
    I came from {`${props.from || ' nowhere'}`} 
 
    <Link to={{pathname: '/', query: {from: 1}}}>State 1 </Link> 
 
    <Link to={{pathname: '/', query: {from: 2}}}>State 2 </Link> 
 
    </div> 
 
) 
 

 
const getComponent = (nextState, next) => { 
 
    next(null, props => <App {...props} from={nextState.location.query.from} />) 
 
} 
 

 
const Root =() => (
 
    <Router history={hashHistory}> 
 
    <Route path="/" exact getComponent={getComponent}/> 
 
    <Redirect from="/js" to="/" /> 
 
    </Router> 
 
) 
 

 
ReactDOM.render(
 
    <Root/>, 
 
    document.querySelector('#app') 
 
)
<script src="https://unpkg.com/[email protected]/dist/react.js"></script> 
 
<script src="https://unpkg.com/[email protected]/prop-types.js"></script> 
 
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script> 
 
<script src="https://unpkg.com/[email protected]/umd/ReactRouter.js"></script> 
 

 

 
<div id="app">Loading</div>

+0

謝謝@yury!一個問題,你爲什麼使用'location'?爲什麼它不只是'nextState.query.form'?是因爲你從鏈接中獲得道具嗎?你還能從哪裏得到道具? – mangocaptain

+1

我只是爲了演示而使用它。有更好的方法來獲取組件中的查詢參數,而不是使用'withRouter'。但是當你需要基於這些參數異步加載組件時,你必須這樣做。順便提一下,你應該記住'getComponent'在react-router v4中被刪除了。 –

0

這裏的下一個狀態是當前狀態或初始狀態,在某些情況下nextState指的是不適用於查看的狀態。所以nextState將是最新的狀態。

例如你設置10狀態var_x,以前它在這種情況下是5

如果你檢查nextState.var_x這將是10和this.state.var_x將是5,經過一番time only this.state.var_x will get updated and value is 10.

+2

誰給的狀態,這條路呢?它的父母路線? – mangocaptain

+0

不,狀態是本地事物,所以你必須設置initailState。道具可以由父母設置 – MehulJoshi

相關問題