使用React Route,但我面临此问题:在某些情况下,我需要该应用加载与实际URL不同的URL。这是我所做的:
class Application extends React.Component {
render() {
const { history } = this.props;
let loadExact = true;
if (my_condition === true) {
loadExact = false;
}
return (
<Dashboard history={history}>
<Switch>
{
loadExact ? <Route exact path="/app" component={MainPage} /> :
(
<Redirect to={{
pathname: "/app/theotherpage",
state: {from: history}
}}
/>
)
}
<Route path="/app/theotherpage" component={TheOtherPage} />
<Route component={NotFound} />
</Switch>
</Dashboard>
);
}
}
我需要的是,如果loadExact
为false
,然后重定向到/app/theotherpage
,然后加载它而不是/app
。这样,它会转到一个完全空白的页面,并告诉我:
无法在已卸载的组件上执行React状态更新。这是空操作,但它表明应用程序中发生内存泄漏。要修复,请取消componentWillUnmount方法中的所有订阅和异步任务。
我该如何解决?
有两种方法可以做到:
通过<Switch>
外部重定向
如果(my_condition === true){loadExact = false;loadComp =;}
return (
<Dashboard history={history}>
{loadComp}
<Switch>
<Route exact path="/app" component={MainPage} />
<Route path="/app/theotherpage" component={TheOtherPage} />
<Route component={NotFound} />
</Switch>
</Dashboard>
);
}}
通过history.push
`类应用程序扩展了React.Component {render(){const {history} = this.props;让loadExact = true;
if (my_condition === true) {
loadExact = false;
this.props.history.push('/app/theotherpage');
}
return (
<Dashboard history={history}>
<Switch>
<Route exact path="/app" component={MainPage} />
<Route path="/app/theotherpage" component={TheOtherPage} />
<Route component={NotFound} />
</Switch>
</Dashboard>
);
}}`
您可以将props loadExact传递给MainPage组件,然后在propsloadExact为false时在该组件内重定向。
<Route
path='/app'
render={(props) => <MainPage {...props} loadExact={loadExact} />}
/>