1

我遵循React路由器4的重定向(Auth)指南,并且无法渲染基于ajax返回的承诺。我不确定为什么我的渲染内容没有被返回。有人能指出我正确的方向吗?反应路由器4异步渲染

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> 
) 
}; 

回答

2

那是因为承诺不能返回值,它只返回承诺。相反,它执行回调。 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; 
     }}/> 
    ) 
    } 
} 

注意,承诺不返回任何东西,它只是执行触发重新呈现在状态新数据的回调。

+0

如何获得与服务器端渲染没有零组件? –