这是一个没有 redux 的例子:
我的页面.jsx
import React from 'react'
import { fetchDataForMyPage } from './someApi'
let data = {}
export default class MyPage extends React.Component {
constructor() {
super()
this.state = {
/* ... */
data: data
/* ... */
}
}
render() {
/* ... */
}
static loadData(routerParams, callback) {
fetchDataForMyPage(routerParams).then((fetchedData) => {
data = fetchedData
callback()
})
}
componentWillReceiveProps() {
this.setState({
data: data
})
}
}
路由.jsx
import React from 'react'
import { Route } from 'react-router'
import App from './components/App'
import MyPage from './components/MyPage'
const loadDataOnEnter = (nextState, replace, callback) => {
const nRoutes = nextState.routes.length
const component = nextState.routes[nRoutes-1].component
const params = nextState.params
component.loadData(params, () => callback())
}
module.exports =
<Route path="/" component={App}>
<Route path="mypage/:param1" component={MyPage} onEnter={loadDataOnEnter} />,
<Route path="anotherpage" component={AnotherPage} onEnter={loadDataOnEnter} />,
<Route path="somepath" component={SomePageWithoutDataPreloading} />
</Route>