React Router 4 异步渲染
Posted
技术标签:
【中文标题】React Router 4 异步渲染【英文标题】:React Router 4 Async Rendering 【发布时间】:2018-02-11 03:07:07 【问题描述】:我正在遵循 React Router 4 for Redirect(Auth) 的指南,但我无法根据 ajax 返回的承诺进行渲染。我不确定为什么我在承诺中的渲染没有被返回。有人能指出我正确的方向吗?
import React from 'react';
import
Route,
Redirect,
withRouter
from 'react-router-dom';
import HeaderContainer from '../containers/HeaderContainer';
const PrivateRoute = ( component: Component, ...props ) =>
const validated = (rest) =>
props.fetchUser()
.then(() =>
return (
<div>
<HeaderContainer />
<Component ...rest/>
</div>
)
)
.catch(()=>
return (
<Redirect to=
pathname: '/signin',
state: from: props.location
/>
)
);
return (
<Route ...props render=rest =>
return (
<div>
validated(rest)
</div>
)
/>
)
export default withRouter(PrivateRoute);
我的路线是这样的
const Root = ( store ) =>
return (
<Provider store= store >
<BrowserRouter onUpdate=() => window.scrollTo(0, 0)>
<div className="root">
<Switch>
<Route exact path="/signin" component=SignInContainer/>
<PrivateRouteContainer exact path="/" component=HomePageContainer />
</Switch>
</div>
</BrowserRouter>
</Provider>
)
;
【问题讨论】:
【参考方案1】:那是因为promise不能返回值,它只返回Promise。相反,它执行回调。 Here is some explanation.
你可以重新排列你的代码,有点像这样:
class PrivateRoute extends React.Component
constructor(props)
super(props);
this.state =
isFetching: true,
isSuccess: null,
;
componentDidMount()
this.props.fetchUser()
.then(() =>
this.setState( isFetching: false, isSuccess: true );
)
.catch(()=>
this.setState( isFetching: false, isSuccess: false );
);
render()
const isFetching, isSuccess = this.state;
return (
<Route ...this.props render=rest =>
const success = (
<div>
<HeaderContainer />
<Component ...rest/>
</div>
);
const error = (
<Redirect to=
pathname: '/signin',
state: from: this.props.location
/>
);
if(isFetching)
return null;
return isSuccess ? success : error;
/>
)
请注意,Promise 不会返回任何内容,它只是执行一个回调,触发使用状态中的新数据重新渲染。
【讨论】:
如何通过服务器端渲染获得无空组件?以上是关于React Router 4 异步渲染的主要内容,如果未能解决你的问题,请参考以下文章