反应路由器4异步渲染

时间:2017-09-02 04:53:14

标签: javascript reactjs asynchronous react-router react-router-v4

我正在遵循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 个答案:

答案 0 :(得分:2)

多数民众赞成因为承诺不能返回价值,它只返回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不会返回任何只是执行回调的内容,这会触发重新呈现状态中的新数据。