【问题标题】:React not updating its state when come back using react-router in Apollo Client在 Apollo 客户端中使用 react-router 返回时 React 未更新其状态
【发布时间】:2017-06-23 12:46:24
【问题描述】:

我正在尝试实现一个场景,我需要添加一个新站点,然后返回站点列表页面,它需要获取新的更新记录。我现在正在使用带有 ReactJS 和 GraphQL 的 Apollo 客户端。

这是我的 siteListContainer 页面。

export default class SitesGrid extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    try {
      let sites = this.props.data.viewer.sites.edges;

      if (sites.length > 0 ) {
        sites = sites.map(item => item.node);
        return (
          <GridView>
            {sites.map(this.renderSiteCard)}
          </GridView>
        );
      }

    } catch (e) {
      console.info('There was an error fetching sites.');
    }

    return (<div />);
  }
}

添加网站表单

class SiteForm extends React.Component {

  // Form on submit
  onSubmit(event) {
      //mutation to create site
      this.props.mutate({
        variables: variables
      }).then(() => {
        browserHistory.push('/app/device-explorer');        
      });
      event.preventDefault();
    }
  };

  render() {
    return (
      <form onSubmit={this.onSubmit}>

        <ListViewItem>
          <label>Site Name</label>
          <input type="text" value={this.state.value} onChange={this.handleChange} className="form-control"
                 aria-describedby="name" placeholder="Site Name"/>
        </ListViewItem>

        <ListViewItem className="text-xs-right">
          <button type="submit" className="btn btn-primary">Submit</button>
        </ListViewItem>

      </form>
    );
  }
}

export default (
  graphql(SiteSaveMutation)(
    graphql(SiteTypeQuery)(
      (SiteForm)
    )
  )
);

【问题讨论】:

    标签: reactjs react-router graphql apollo


    【解决方案1】:

    在 GraphQL 中,很难判断哪些查询需要在突变后自动重新获取,因此您需要告诉 Apollo 要做什么。

    实现这一点的最简单方法是在您的查询容器中设置cache-and-networkfetch policy,然后它会在您返回时重新获取(默认情况下,它使用缓存)。看起来像:

    export default (
      graphql(SiteSaveMutation)(
        graphql(SiteTypeQuery, { options: { fetchPolicy: 'cache-and-network' } })(
          (SiteForm)
        )
      )
    );
    

    您也可以使用refetchQueriesupdateQueries

    【讨论】:

      猜你喜欢
      • 2021-07-30
      • 1970-01-01
      • 2021-12-04
      • 2020-02-03
      • 2017-09-19
      • 2018-08-26
      • 2018-05-19
      • 2020-03-30
      • 1970-01-01
      相关资源
      最近更新 更多