使用react js在Apollo客户端中更改道具时未调用的查询

时间:2017-12-06 05:10:42

标签: reactjs apollo react-apollo apollo-client

我需要在redux商店中更新道具时调用查询。但是没有发生这种情况,只在加载组件时调用一次查询。

我的代码是这样的 - -

  const sampleData = compose(graphql(ITEMS_BY_CATEGORY, {name:"itemByCategory", options: (props) => ({variables: {_id:props.user._id,searchstring:"", start:0,limit:10, itemype:"created",categoryid:props.categoryid}})}))(samplePage)

export default connect(
  (state) => ({user: state.user.user,categoryid: state.item.categoryid}),
  {}
)(sampleData);

我在道具更新后尝试了重新获取方法。喜欢 - this.props.data.refetch()。但它也没有用。

1 个答案:

答案 0 :(得分:1)

添加componentWillReceiveProps()并在那里调用查询。只要组件收到新的道具,它就会运行。如果您需要使用查询结果重新运行render函数,则可能需要调用forceUpdate();

componentWillReceiveProps(nextProps) {
       const localThis = this;  
       this.client.query({
            query: MY_QUERY,
            variables: {myVar: theVar},
        }).then((result) => {
            localThis.setState({myStateVar: result.data.relevantData});
            localThis.forceUpdate();
        });
  }