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

如何獲得與服務器端渲染沒有零組件? –