使用react,react-router和redux实现面包屑

时间:2017-05-19 15:23:14

标签: redux react-router breadcrumbs

我在下面设计了动作和减速器:

// Action Types
const PUSH_BREADCRUMB = 'PUSH_BREADCRUMB';
const POP_BREADCRUMB = 'POP_BREADCRUMB';

// ActionCreator
const pushBreadcrumb = (payload: { text, link }) => ({
  type: PUSH_BREADCRUMB,
  payload
});
const popBreadcrumb = () => ({ type: PUSH_BREADCRUMB });

// Reducer
const initState = [
  { text: 'Home', link: '/' }
];
const breadcumbsReducer = (state = initState, action) => {
  switch (action.type) {
    case PUSH_BREADCRUMB:
      return [...state, action.payload];
    case POP_BREADCRUMB:
      return state.slice(0, state.length - 1);
    default:
      return state
  };
};

以下是我的组件和路由器:     //...import一些组件

// ...connect and map breadcrumbs
const Header = ({ breadcrumbs }) => {
  return (
    <ul>
      {breadcrumbs.map({ item, link } =>
        <li key={link}><Link to={link}>{text}</Link></li>
      )}
    </ul>
  );
};

ReactDOM.render(
  <Provider>
    <Router>
      <AppContainer>
        <Header />
        <Route exact path='/orders' component={OrderListContainer} />
        <Route path='/orders/:id' component={OrderDetailContainer} />
      </AppContainer>
    </Router>
  </Provider>,
  document.getElementById('root')
);

然后:

  • pushBreadcrumbOrderListContainer#componenetWillMount

  • 中发送OrderDetailContainer#componenetWillMount
  • popBreadcrumbOrderListContainer#componentWillUnmount中发送OrderDetailContainer#componentWillUnmount

除外的面包屑是Home > Orders > Detail;

但是当我留在/orders/:id并刷新页面时,它将是Home > Detail

使用redux实现面包屑是否有更好的方法?

1 个答案:

答案 0 :(得分:0)

发生这种情况是因为刷新后状态被重置。您可以尝试使用persistent store实施解决方案-这样会将选定的状态键保留在浏览器的localStorage中。