【问题标题】:Access history in nested component [ReactJS]嵌套组件中的访问历史记录 [ReactJS]
【发布时间】:2017-10-30 00:01:15
【问题描述】:

我有一个从模板构建的 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)
        })
      }
    }
    ,
    ...
  ]
};

routes/ticketing/containers/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 />
    )
  }
}

【问题讨论】:

标签: reactjs react-router


【解决方案1】:

您可以使用withRouter HOC 包装您的组件以访问历史对象。

更多细节在这里: https://reacttraining.com/react-router/web/api/withRouter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-25
    • 2014-06-10
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 2013-05-21
    相关资源
    最近更新 更多