我有一个总是需要渲染的组件,但只有在没有匹配的路由时才应该可见(<Iframe isVisible={ifNoRoutesMatched} />
)。
到目前为止,我还没有找到一个很好的方法来检查是否是这种情况。我走下了这条可怕的路线,将变量设置为组件包装器状态,但必须有更好的方法!?这也需要 withRouter
和 PureComponent
否则 catchAllWrapper
导致无限渲染循环:
class App extends PureComponent {
state = {
routeMatched: false,
}
catchAllWrapper = () => {
this.setState({ routeMatched: false });
return null;
}
routeWrapper = (RouteComponent) => {
const RouteWrapper = (props) => {
this.setState({ routeMatched: true });
return <RouteComponent {...props} />;
};
return RouteWrapper;
}
render() {
return (
<div className="App">
<Navigation />
<Switch>
<Route path="/chat" component={this.routeWrapper(Chat)} />
...more routes...
<Route component={this.catchAllWrapper} />
</Switch>
<Iframe isVisible={!this.state.routeMatched} />
</div>
);
}
}
export default withRouter(App);
我宁愿手动比较路由字符串数组也不愿增加这种复杂性!
this.props.match
只有在匹配组件内部匹配的路由信息,所以它非常无用。
有更好的方法吗?
用例:它是一个 iframe,在某些路由上加载了旧版应用程序,因此不应在路由之间销毁和重新呈现它
最佳答案
为什么不为路由器创建一个轻量级虚拟组件以自由挂载和卸载,然后将当前类的回调方法绑定(bind)到它的生命周期事件?
class Dummy extends Component {
componentDidMount() {
this.props.didMount();
}
componentWillUnmount() {
this.props.willUnmount();
}
render() {
return null;
}
}
class App extends Component {
state = {
showIframe: false,
}
cbDidMount = () => {
this.setState({ showIframe: true });
}
cbWillUnmount = () => {
this.setState({ showIframe: false });
}
render() {
return (
<div className="App">
<Navigation />
<Switch>
<Route path="/chat" component={Chat} />
{/* more routes */}
<Route render={() => <Dummy didMount={this.cbDidMount} willUnmount={this.cbWillUnmount} />} />
</Switch>
<Iframe isVisible={this.state.showIframe} />
</div>
);
}
}
关于javascript - react 路由器 v4 : Determine if route has been matched from outside the component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53325062/