Reactjs apollo客户端查询保护路由
我正在尝试在我的graphql react应用程序中使用私有路由方法应用受保护路由。我正在使用apollo客户端2 专用路由按预期工作,即它保护/防止某人手动输入url(在本例中为/surveys)。但是,当手动重新加载或刷新页面时,graphql查询最初将返回空的对象数据(当用户登录时)或未定义的数据。因此,专用路由内的重定向条件被应用,因此客户端被重定向到“/”路径。这有什么关系吗?这是我的应用程序和我的私人路线代码:Reactjs apollo客户端查询保护路由,reactjs,react-router,react-apollo,apollo-client,Reactjs,React Router,React Apollo,Apollo Client,我正在尝试在我的graphql react应用程序中使用私有路由方法应用受保护路由。我正在使用apollo客户端2 专用路由按预期工作,即它保护/防止某人手动输入url(在本例中为/surveys)。但是,当手动重新加载或刷新页面时,graphql查询最初将返回空的对象数据(当用户登录时)或未定义的数据。因此,专用路由内的重定向条件被应用,因此客户端被重定向到“/”路径。这有什么关系吗?这是我的应用程序和我的私人路线代码: /* app.js */ ....imports const WHOA
/* 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;
/*app.js*/
……进口
常量WHOAMI=gql`
查询whoAmI{
哇{
_身份证
电子邮件
}
}
`;
类应用程序扩展组件{
render(){
返回(
{({加载,错误,数据})=>{
//控制台日志(数据);
返回(
);
}}
);
}
}
导出默认应用程序;
还有我的私人档案
...imports
const PrivateRoute = ({ component: Component, userId, ...rest }) => (
<Route {...rest} render={props => (
!userId || userId === 'undefined' ? (
<Redirect to={{
pathname: '/'
}}
/>
) : (
<Component {...props} />
)
)} />
);
export default PrivateRoute
…导入
const privaterout=({component:component,userId,…rest})=>(
(
!userId | | userId==‘未定义’(
) : (
)
)} />
);
导出默认PrivateRoute
我可能有相同的体系结构,我也有
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>
}
}
类应用程序扩展组件{
构造函数(…参数){
超级(…args)
此.state={
用户:{},
加载:正确
}
}
componentDidMount(){
fetchUser()
。然后(用户=>{
这是我的国家({
用户,
加载:错误
})
})
}
渲染(){
if(this.state.loading){
返回
}否则{
返回(
...
}
}
您好,我正在尝试使用Apollo来管理我的状态,而不是redux,我认为我的问题的解决方案可能与本地状态的新Apollo链接状态有关management@scubadude我在我的示例中根本没有使用Redux,概念是一样的,您只需检查数据。加载查询的内部呈现,并基于此您将返回BrowserRouter或显示加载的特殊组件。