【问题标题】:How to pass a variables for refetchQueries in Apollo如何在 Apollo 中为 refetchQueries 传递变量
【发布时间】:2018-10-09 14:01:56
【问题描述】:

我不确定在 refetchQueries 选项中传递 variables 的最佳做法是什么。在下面的例子中,变量是{id: this.props.item.id}

但是传递this.props.item.id 返回了一个错误,因为MyComponent 尚未实例化,因此this.props 未定义。

function mapStateToProps(state) {
  return {
    item: state.item
  };
}

MyComponent = connect(mapStateToProps, matchDispatchToProps)(
  MyComponent
);

MyComponent = graphql(createItemImage, {
  name: "createItemImage",
  options: {
    refetchQueries: [
      {
        query: getEntity,
        variables: { id: this.props.item.id }
      }
    ]
  }
  })(MyComponent);

id 值仅在运行时可用。

提前致谢!

【问题讨论】:

    标签: reactjs apollo


    【解决方案1】:

    这是最后的工作,参考ownProps和顺序(connect语句应该graphql语句之后)

    MyComponent = graphql(createItemImage, {
      name: "createItemImage",
      options: ownProps => ({
        refetchQueries: [
          {
            query: getEntity,
            variables: { id: ownProps.item.id }
          }
        ]
      })
    })(MyComponent);
    
    MyComponent = connect(mapStateToProps, matchDispatchToProps)(
      MyComponent
    );
    

    【讨论】:

      【解决方案2】:

      您需要将 item.id 变量显式传递给组件。因此在函数中添加一个变量命名id

       MyComponent = graphql(createItemImage, {
        name: "createItemImage",
        options: {
          refetchQueries: [
            {
              query: getEntity,
              variables: { id: id }
            }
          ]
        }
      })(MyComponent, id);
      
      export default MyComponent
      

      然后在调用组件时使用如下语法

      <MyComponent id={this.props.item.id}>
      

      希望对你有帮助

      【讨论】:

      • 对不起,但这不是问题。我知道我需要通过 item={id: 123} 在调用 MyComponent 例如&lt;MyComponent item={id:123}/&gt;... 但它在编译时失败并出现以下错误 TypeError: Cannot read property 'item' of undefined 因为 this.props 未定义
      • 对不起!糟糕的是,我在组件内部使用了 this.props,在这种情况下我们必须在这里直接使用 id。无需通过 this.props 使用它。已更新代码。注意:由于我们没有从 React 扩展我们的组件,组件将不会接收生命周期函数和 props 变量
      猜你喜欢
      • 2018-08-16
      • 2021-06-09
      • 2019-09-02
      • 2019-10-14
      • 2023-03-15
      • 2020-02-14
      • 2020-04-28
      • 2020-02-17
      • 2020-09-25
      相关资源
      最近更新 更多