我有一个我从模板构建的ReactJS应用程序。我不熟悉反应,更不用说如何使用这种模式加载组件了。
如何从嵌套组件路径中访问history
?
app.js
const routes = {
path: '/',
indexRoute: { onEnter: (nextState, replace) => replace('/login') },
childRoutes: [
require('./routes/ticketing').default,
require('./routes/promotions').default,
...
]
};
ReactDOM.render((
<Provider store={store}>
<Router
history={history}
routes={routes}
/>
</Provider>
), document.getElementById('app'));
路由/售票/ index.js
export default {
path: 'ticketing',
component: require('../../components/common/Layout').default,
indexRoute: { onEnter: (nextState, replace) => replace('/ticketing/printtickets') },
childRoutes: [
{
path: 'printtickets',
getComponent(nextState, cb){
System.import('./containers/printtickets').then((m)=> {
cb(null, m.default)
})
}
}
,
...
]
};
路由/售票/容器/ printtickets.js
import React from 'react'
export default class PrintTickets extends React.Component {
componentWillMount(){
const { history } = this.props; // THIS IS NULL
history.replaceState(null, 'analytics/dashboard') // ERROR
}
render() {
return (
<div />
)
}
}
答案 0 :(得分:1)
您可以使用withRouter
HOC包装组件以访问历史记录对象。
此处有更多详情: https://reacttraining.com/react-router/web/api/withRouter