我想在更改路线时更改菜单状态,但是无法使其工作。
我面临的问题:当我单击导航栏中的链接时。路线改变了,但不会关闭。更改路线后如何更改菜单状态? react-router-redux可以帮助我吗?
动作
export function menuToggle(currentState) {
return {
type: 'MENU_TOGGLE',
payload: {
ToggleMenu: !currentState,
},
};
}
减速器
const initialState = {
showMenu: false,
};
export const MenuToggle = (state = initialState, action) => {
switch (action.type) {
case MENU_TOGGLE:
return {
showMenu: action.payload.ToggleMenu,
};
default:
return state;
}
};
组件
class Header extends Component {
componentWillMount() {
document.addEventListener('click', this.handleClickOutside, false);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClickOutside, false);
}
handleClickOutside = e => {
if (!ReactDOM.findDOMNode(this).contains(e.target)) {
this.props.showMenu === true && this.props.menuToggle(!false);
}
};
render() {
return (
<Head>
<Brand>BRAND</Brand>
<MenuButton
onClick={this.props.menuToggle.bind(null, this.props.showMenu)}
>
MENU
</MenuButton>
<MobileMenu showMenu={this.props.showMenu} />
</Head>
);
}
}
const mapStateToProps = state => {
return {
showMenu: state.MenuToggle.showMenu,
};
};
const mapDispatchToProps = { menuToggle };
export default connect(
mapStateToProps,
mapDispatchToProps,
)(Header);
儿童组件
const MobileMenu = ({ showMenu }) => {
return (
showMenu === true && (
<Nav>
<Ul>
<Li>
<A to="/">
<Span>Home</Span>
</A>
</Li>
<Li>
<A to="/shop">
<Span>Shop</Span>
</A>
</Li>
<Li>
<A to="/contact">
<Span>Contact</Span>
</A>
</Li>
</Ul>
</Nav>
)
);
};
export default MobileMenu;
答案 0 :(得分:0)
是的,react-router-redux可以为您提供帮助。 您可以在减速器中收听LOCATION_CHANGE,然后关闭“ showMenu”。