【问题标题】:apollo client query protected route阿波罗客户端查询保护路由
【发布时间】:2018-09-12 23:44:45
【问题描述】:

我正在尝试在我的 graphql react 应用程序中使用私有路由方法应用受保护的路由。我正在使用 apollo 客户端 2。

私有路由按预期工作,即它保护/防止某人手动输入 url(在本例中为 /surveys)。但是,当手动重新加载或刷新页面时,graphql 查询最初会返回一个空对象数据(当用户登录时)或未定义的数据。因此,应用了私有路由内的重定向条件,因此客户端被重定向到“/”路径。有没有办法解决?这是我的应用程序和我的私人路线代码:

/* app.js */
....imports

const WHOAMI = gql`
  query whoAmI {
    whoAmI {
      _id
      email
    }
  }
`;

class App extends Component {
  render() {
    return (
      <div>
        <BrowserRouter>
          <div>
            <Header />
            <Query query={WHOAMI}>
              {({ loading, error, data }) => {
                // console.log(data);
                return (
                  <div className="container">
                    <div className="col s12 center-align">
                      <Switch>
                        <Route path="/surveys/new" component={SurveyNew} />
                        <PrivateRoute
                          path="/surveys"
                          userId={data.whoAmI}
                          component={SurveyList}
                        />
                        <Route path="/" exact component={LandingPage} />
                      </Switch>
                    </div>
                  </div>
                );
              }}
            </Query>
          </div>
        </BrowserRouter>
      </div>
    );
  }
}

export default App;

还有我的 PrivateRouter 文件

...imports 

const PrivateRoute = ({ component: Component, userId, ...rest }) => (  
  <Route {...rest} render={props => (
    !userId || userId === 'undefined' ? (
      <Redirect to={{
        pathname: '/'
        }}
      />
    ) : (
      <Component {...props} />
    )
  )} />
);


export default PrivateRoute

【问题讨论】:

    标签: reactjs react-router react-apollo apollo-client


    【解决方案1】:

    我的架构可能和我一样

    class App extends Component {
      constructor (...args) {
        super(...args)
    
        this.state = {
          user: {},
          loading: true
        }
      }
    
      componentDidMount() {
        fetchUser()
          .then(user => {
            this.setState({
              user,
              loading: false
            })
          })
      }
    
      render () {
        if (this.state.loading) {
          return <LoadingPage />
        } else {
          return (
            <ApolloProvider client={client}>
              <BrowserRouter>
                ...
              <BrowserRouter />
            </ApolloProvider>  
        }
    }
    

    【讨论】:

    • 嗨,我正在尝试使用 Apollo 来管理我的状态而不是 redux,我认为我的问题的解决方案可能与用于本地状态管理的新 apollo-link-state 有关跨度>
    • @scubadude 好吧,我的示例中根本没有使用 Redux,概念是一样的,您只需检查 Query 的 data.loading 内部渲染,并根据此条件返回 BrowserRouter ,或显示正在加载的特殊组件。
    猜你喜欢
    • 2020-07-26
    • 2020-03-23
    • 2019-02-15
    • 2021-06-28
    • 2019-02-09
    • 2019-05-19
    • 2018-10-03
    • 1970-01-01
    • 2021-04-03
    相关资源
    最近更新 更多