反应:直到页面刷新后数据才显示

时间:2019-02-18 16:41:02

标签: reactjs graphql apollo react-apollo apollo-client

我目前正在使用React和GraphQL构建一个简单的CRUD工作流程。创建对象(本例中为articleidtitle的对象(在本例中为description)之后,我导航回到Index页面显示所有当前创建的文章。我的问题是创建文章后,索引页面在刷新页面之前不会显示创建的文章。我正在使用apollo来查询graphql api并禁用了缓存,因此我不确定为什么不显示数据。我在ArticlesIndex的{​​{1}}函数中设置了断点,并确保它正在执行,并且在执行时,数据库确实包含新添加的componentDidMount

实际上,执行检索所有文章的客户端查询时,我的服务器端甚至从未命中。我不确定是什么在缓存此数据,以及为什么未按预期从服务器检索到数据。

我的article组件插入新记录,并重定向回ArticlesCreate组件,如下所示:

ArticlesIndex

然后我的handleSubmit(event) { event.preventDefault(); const { client } = this.props; var article = { "article": { "title": this.state.title, "description": this.state.description } }; client .mutate({ mutation: CREATE_EDIT_ARTICLE, variables: article }) .then(({ data: { articles } }) => { this.props.history.push("/articles"); }) .catch(err => { console.log("err", err); }); } } 组件从数据库中检索所有文章,如下所示:

ArticlesIndex

并且我将ApolloClient设置为不像在componentDidMount = () => { const { client } = this.props; //client is an ApolloClient client .query({ query: GET_ARTICLES }) .then(({ data: { articles } }) => { if (articles) { this.setState({ loading: false, articles: articles }); } }) .catch(err => { console.log("err", err); }); }; 中那样缓存数据,如下所示:

App.js

为什么会这样,我该如何解决?

2 个答案:

答案 0 :(得分:1)

看来ApolloBoost不支持in this github issuedefaultOptions不支持const defaultApolloOptions = { watchQuery: { fetchPolicy: 'network-only', errorPolicy: 'ignore', }, query: { fetchPolicy: 'network-only', errorPolicy: 'all', }, } export default class App extends Component { displayName = App.name; client = new ApolloClient({ uri: "https://localhost:44360/graphql", cache: new InMemoryCache(), defaultOptions: defaultApolloOptions }); //...render method, route definitions, etc } 。要解决我更改的问题,

const client = new ApolloClient({
  uri: "https://localhost:44360/graphql"
});

client.defaultOptions = {
  watchQuery: {
    fetchPolicy: 'network-only',
    errorPolicy: 'ignore',
  },
  query: {
    fetchPolicy: 'network-only',
    errorPolicy: 'all',
  },
};

export default class App extends Component {
    //....
}

收件人:

implode()

答案 1 :(得分:0)

我可以看到您正在获取数据并在初始安装时设置组件的状态。很有可能在您重定向时,它不会触发已经挂载的componentDidMount生命周期钩子,如果这是问题所在,请尝试使用componentDidUpdate生命周期钩子,以使您的组件知道有更新并重新设置数据。

相关问题