如何在 React 中使用 Redux Store 和 GraphQl 进行查询

Posted

技术标签:

【中文标题】如何在 React 中使用 Redux Store 和 GraphQl 进行查询【英文标题】:How to Query with Redux Store and GraphQl in React 【发布时间】: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); 【参考方案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,我得到了答案

【讨论】:

以上是关于如何在 React 中使用 Redux Store 和 GraphQl 进行查询的主要内容,如果未能解决你的问题,请参考以下文章

在 react js 功能组件中调度操作后如何立即在 redux store 中使用更新的值

如何在react中用redux组织store?

我如何在 react redux 中访问另一个 reducer 的状态。 reducer 和 store 之间的状态流

React GraphQL Apollo 和 Redux。如何查询数据并将其置于 store 的 initialState 中?

如何在Redux中使用React Context API?

React-redux mapStateToProps,mapDispatchToProps 如何使用