这是文档中的一个示例-nextState来自哪里?

<Route path="courses/:courseId" getComponents={(nextState, cb) => {
  // do asynchronous stuff to find the components
  cb(null, {sidebar: CourseSidebar, content: Course})
}} />

最佳答案

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>

09-07 17:30