我有以下两个组成部分
SongList.js
import React, { Component } from 'react';
import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
import { Link } from 'react-router';
class SongList extends Component {
renderSongs() {
return this.props.data.songs.map(song => {
return (
<li key={song.id} className="collection-item">
{song.title}
</li>
);
});
}
render() {
if (this.props.data.loading) {
return <div>Loading...</div>;
}
return (
<div>
<ul className="collection">
{this.renderSongs()}
</ul>
<Link
to="/songs/new"
className="btn-floating btn-large red right"
>
<i className="material-icons">add</i>
</Link>
</div>
);
}
}
const query = gql`
{
songs {
id,
title
}
}
`;
export default graphql(query)(SongList);
SongCreate.js
import React, { Component } from 'react';
import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
import { Link, hashHistory } from 'react-router';
class SongCreate extends Component {
constructor(props) {
super(props);
this.state = { title: '' }
}
onSubmit(event) {
event.preventDefault();
this.props.mutate({
variables: {
title: this.state.title
}
}).then(() => hashHistory.push('/'));
// .catch((err) => console.log('DEBUG::err', err));
}
render() {
return (
<div>
<Link to="/">
Back
</Link>
<h3>Create a New Song</h3>
<form onSubmit={this.onSubmit.bind(this)}>
<label>Song Title: </label>
<input
onChange={event => this.setState({ title: event.target.value })}
value={this.state.title}
/>
</form>
</div>
);
}
}
const mutation = gql`
mutation AddSong($title: String){
addSong(title: $title) {
title
}
}
`;
export default graphql(mutation)(SongCreate);
基本上我遇到的情况是,在SongCreate
组件中,一旦成功更改了addSong
方法,它将导航回到SongList
,但是,我看不到SongList
上的一首新歌,为了让我看到,我必须刷新页面。在我看来,SongList
处的查询没有被调用?
答案 0 :(得分:1)
您需要在突变结果和查询结果上查询相同的字段。这样,阿波罗的内部缓存将相应地更新(see doc section)
const mutation = gql`
mutation AddSong($title: String){
addSong(title: $title) {
id <==== Added this to match the query
title
}
}
`;
我还建议您使用the chrome extension来查看阿波罗缓存
答案 1 :(得分:0)
看来,由于查询执行一次的原因,并且当您添加新项目并路由回到列表页面时,由于缓存,查询将不会重新运行。因此,为了解决该问题,我们可以重新获取查询。
在SongCreate
组件中,我们可以在refetchQueries
内定义mutate
,如下所示:
this.props.mutate({
variables: {
title: this.state.title
},
refetchQueries: [{ query: gql`.........` }] //<======
}).then(() => hashHistory.push('/'));