【问题标题】:How to Query with Redux Store and GraphQl in React如何在 React 中使用 Redux Store 和 GraphQl 进行查询
【发布时间】:2017-12-29 19:27:04
【问题描述】:

我的 GraphQl Query and Mutation 调用有问题。我为这样的应用程序构建了一个组件

class ABC extends Component {
   componentDidMount(){
      this.props.eventuser({
        variables: {
            eventName: {id:this.props.activeEvent.cell.id}

        },

    }).then(response => {
        //response ...
    }).catch(err =>{
        console.log('Error',err);
    });
   }
   render(){
     some render things
   }
}
function mapStateToProps(store) {
   return {
        activeEvent: store.activeEvent
   };
}
const Save= connect(mapStateToProps)(ABC);
export default compose(
graphql(Query1,
   name:"eventuser"
   }),
graphql(Query2,{
   name:"alluser"
   }),
graphql(Mutation1,{
   name:"updateEventdata"
   }))(Save);

查询需要带有activeEvent的ID。
我现在的问题是,GraphQl 在 activeEvent id 出现之前就已经存在(我认为是这样)。

我不得不重新构建应用程序的这一部分以重新获取,而 react-apollo 的正常 withApollo() 函数没有类似的东西(或者我没有找到它)。
所以代码看起来有点乱,因为它是旧代码和“新”代码的片段。

如果有可能使用 withApollo() 重新获取,我想继续这样做。否则我需要帮助将 activeEvent 的 ID 注入为 Query 和 Prop/State/Variable

附加信息:

  • 有一个 redux 存储,其中包含 ID 和其他一些东西
  • 它是应用程序的一个组件,而不是完整的应用程序

【问题讨论】:

  • 在你的 reducer 中尝试为 { activeEvent: { cell: { id: '"" } } } 添加初始状态。这应该会阻止它在组件首次渲染时抛出一个。
  • 已经有一个初始状态了,问题不是没有找到什么的,问题是查询没有id,但是已经派发了。调度是在组件更改之前,所以通常它已经存在,但是 graphql 函数无法访问属性(我认为)。 “connect()”是在调用 grapql() const Save= connect(mapStateToProps)(ABC); export default compose("graphql bla")(Save);

标签: reactjs graphql apollo


【解决方案1】:

所以我找到了一种解决问题的方法。您需要通过父元素将 ID 作为道具传递。看起来像这样:
App.js
//call of the Event, passes the eventID from the Redux to the child element <Eventoverview eventName={this.props.activeEvent.cell.id} />
然后在子元素中,graphql 导出如下所示:
Eventoverview.js
export default compose(
connect(mapStateToProps)
,graphql(Query1,{
options: (props)=>({ variables: { eventName: {id:props.eventName}},}), name:"eventuser"
}),graphql(Query2,{ name:"alluser"
}),graphql(Mutation1,{ name:"updateEventdata"
}))(Eventoverview);

现在在查询中使用了 ID,我得到了答案

【讨论】:

    猜你喜欢
    • 2018-06-24
    • 2020-12-04
    • 2018-06-03
    • 2018-05-08
    • 2020-05-13
    • 2017-02-10
    • 2016-11-30
    • 2015-11-27
    相关资源
    最近更新 更多