路由更改期间React Redux fire action

时间:2017-05-12 18:00:53

标签: reactjs redux router

我正在使用“react-router”:“^ 4.1.1”,我能够在我的项目中成功运行。现在我需要在路由更改时触发和操作。我该怎么办?

/ index.js /

render((
    <Provider store={store}>
    <BrowserRouter>
      <div>
        <HeaderContainer />
        <Main />
      </div>
    </BrowserRouter>


    </Provider>),

  document.getElementById('root')
)

/ Main.js /

class Main extends React.Component {
    render() {
        return (
              <main>
                <Switch>
                  <Route exact path='/' component={Menu}/>
                  <Route path='/subMenu' component={subMenu}/>
                  <Route path='/Dummy' component={Dummy}/>
                </Switch>
              </main>
            );
        }
    }

export default Main;

/ 组件/ product.js /

const Product = ({ ImageUrl, price, quantity, Title, ID }) => (

    <div className="grid_item menuCategoryList_item">
      <Link to='/subMenu' data-productid= {ID} data-id="menuOrderModal" className="js-openModalOverlay">
        {<div className="menuCategoryList_photo"><img src={ImageUrl} alt=""/></div>}
      </Link>
    </div>

)

现在我的reducer捕获了一个触发的动作,它负责填充数据。如何在路由发生时触发操作?

1 个答案:

答案 0 :(得分:0)

通常有两种方式:

1)内部组件

 import { browserHistory } from 'react-router';

  //Your initialization

  browserHistory.listen( location =>  {
   //Do your stuff here
  });

2)在根组件中

  <Route path="/" onChange={yourHandler} component={AppContainer}>
     <IndexRoute component={StaticContainer}  />
     <Route path="/a" component={ContainerA}  />
     <Route path="/b" component={ContainerB}  />
   </Route>

  function yourHandler(previousRoute, nextRoute) {
     //do your logic here
  }