Reactjs 我如何将阿波罗数据和路由器4 url参数传递给我的组件
我正在使用react路由器V4和apollo客户端。我有几条被认为是私人路线。我在它们自己的组件中有这些路由。我使用withRouter()包装PrivateRoute组件,以便将所有路由内容传递下去。我还将其包装在graphql查询中,以便知道用户已登录。我的问题是,我似乎无法同时从graphql和路由数据中获取数据 通过这种方式定义路线,我获得了apollo数据,但没有匹配:idReactjs 我如何将阿波罗数据和路由器4 url参数传递给我的组件,reactjs,routing,react-router-v4,apollo,Reactjs,Routing,React Router V4,Apollo,我正在使用react路由器V4和apollo客户端。我有几条被认为是私人路线。我在它们自己的组件中有这些路由。我使用withRouter()包装PrivateRoute组件,以便将所有路由内容传递下去。我还将其包装在graphql查询中,以便知道用户已登录。我的问题是,我似乎无法同时从graphql和路由数据中获取数据 通过这种方式定义路线,我获得了apollo数据,但没有匹配:id } /> 如果我改变路线到这里,我会得到参数id,但道具中没有阿波罗数据 这是我的主要路线部分 cons
} />
如果我改变路线到这里,我会得到参数id,但道具中没有阿波罗数据
这是我的主要路线部分
const Routes = () => (
<Router>
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/login" component={Login} />
<Route path="/create-account" component={CreateUser} />
<PrivateRouteContainer />
</Switch>
</div>
</Router>
);
const Routes=()=>(
);
这是我的私人航线和私人航线集装箱
class PrivateRoute extends Component {
render() {
if (this.props.data.loading) {
return <Loading />;
} else if (this.props.data.user) {
return (
<div>
<VerticalNavFixed />
<article className="docs-content">
<Switch>
<Route {...this.props} exact path="/people/:id" component={Person} />
</Switch>
</article>
</div>
);
}
return <Redirect to={{ pathname: '/login', state: { from: this.props.location } }} />;
}
}
const PrivateRouteContainer = graphql(userQuery, { options: { fetchPolicy: 'network-only' } })(withRouter(PrivateRoute));
类PrivateRoute扩展组件{
render(){
if(this.props.data.load){
返回;
}else if(this.props.data.user){
返回(
);
}
返回;
}
}
const PrivateRouteContainer=graphql(userQuery,{options:{fetchPolicy:'network only'}})(withRouter(PrivateRoute));
一种解决方案是在React.cloneElement
函数中组合路由器道具和查询道具。在您的情况下,它可能如下所示:
类PrivateRoute扩展组件{
render(){
if(this.props.data.load){
返回;
}else if(this.props.data.user){
返回(
{return React.cloneElement(,{user:this.props.data.user,…props}}}/>
);
}
返回;
}
}
const PrivateRouteContainer=graphql(userQuery,{options:{fetchPolicy:'network only'}})(withRouter(PrivateRoute))
一种解决方案是在React.cloneElement
函数中组合路由器道具和查询道具。在您的情况下,它可能如下所示:
类PrivateRoute扩展组件{
render(){
if(this.props.data.load){
返回;
}else if(this.props.data.user){
返回(
{return React.cloneElement(,{user:this.props.data.user,…props}}}/>
);
}
返回;
}
}
const PrivateRouteContainer=graphql(userQuery,{options:{fetchPolicy:'network only'}})(withRouter(PrivateRoute))代码>事实证明,我的路由已经将用户推送到了它,这就是确保路由安全所需的全部内容。另外,我需要将我的其他组件包装在不同的查询中,因此我不需要将现有的查询数据传递给该组件。我同意这个
}/>
然后在我的组件中,我在选项中用params变量包装它,这使得查询等待这个param
export const PersonWithData = graphql(PersonQuery, {
options: ownProps => ({ variables: { id: ownProps.match.params.id } }),
})(Person);
事实证明,我的路由已经将用户推送到了它,这就是确保路由安全所需的全部。另外,我需要将我的其他组件包装在不同的查询中,因此我不需要将现有的查询数据传递给该组件。我同意这个
}/>
然后在我的组件中,我在选项中用params变量包装它,这使得查询等待这个param
export const PersonWithData = graphql(PersonQuery, {
options: ownProps => ({ variables: { id: ownProps.match.params.id } }),
})(Person);
谢谢,我还发布了我使用的解决方案。我现在不想使用React.cloneElement。谢谢,我还发布了我使用的解决方案。我现在不想使用React.cloneElement。