我正在创建带有多个选项的标头,具体的选项将根据URL路径名(例如“ plant / tree”)将类别设置为“ active”。为此,我设置了HeaderOptions组件,并将所有选项的状态初始化的布尔值设置为false(索引上没有任何选项处于活动状态)。我已经实现的逻辑在导航到特定路径名时起作用,但是当返回索引时,它给了我无限循环-我无法解决该问题的解决方案。
const Header = (props) => {
const {
location,
history,
} = props;
return (
<div className="Header">
<div className="grid-row">
<HeaderOptions location={location} history={history} />
</div>
</div>
);
};
const HeaderWithRouter = withRouter(Header);
class HeaderOptions extends React.Component {
state = {
treeOption: false,
prairieOption: false,
reportOption: false,
};
componentDidUpdate() {
const {
treeOption,
prairieOption,
reportOption,
} = this.state;
const {
location: {
pathname,
},
} = this.props;
if (pathname.includes('/plant/tree') && !treeOption) {
this.setOptionState('treeOption');
} else if (pathname.includes('/plant/prairie') && !prairieOption) {
this.setOptionState('prairieOption');
} else if (pathname.includes('/report') && !reportOption) {
this.setOptionState('reportOption');
} else if (pathname === '/') {
this.setOptionState(null);
}
}
setOptionState(optionName) {
const updateState = {
treeOption: false,
prairieOption: false,
reportOption: false,
};
if (optionName) {
updateState[optionName] = true;
}
this.setState(updateState);
}
...
答案 0 :(得分:1)
componentDidUpdate(pathname: string) {
.....
} else if (pathname === "/" && (treeOption || prairieOption || reportOption)) {
this.setOptionState(null);
}
}