如何在Apollo中为refetchQueries传递变量

iwa*_*wan 4 apollo reactjs

我不确定最佳做法是variables采用refetchQueries期权。在下面的示例中,变量为{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);
Run Code Online (Sandbox Code Playgroud)

id值仅在运行时可用。

提前致谢!

iwa*_*wan 7

这是最后的作品,是指ownProps与秩序(connect的说法应该是之后graphql语句)

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

MyComponent = connect(mapStateToProps, matchDispatchToProps)(
  MyComponent
);
Run Code Online (Sandbox Code Playgroud)


min*_*laj 4

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

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

export default MyComponent
Run Code Online (Sandbox Code Playgroud)

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

<MyComponent id={this.props.item.id}>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助