2017-06-15 78 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

相关问题