我在下面设计了动作和减速器:
// 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')
);
然后:
在pushBreadcrumb
和OrderListContainer#componenetWillMount
OrderDetailContainer#componenetWillMount
在popBreadcrumb
和OrderListContainer#componentWillUnmount
中发送OrderDetailContainer#componentWillUnmount
。
除外的面包屑是Home > Orders > Detail
;
但是当我留在/orders/:id
并刷新页面时,它将是Home > Detail
。
使用redux实现面包屑是否有更好的方法?