在我发送了一个delete突变后,我在让React+Apollo更新商店时遇到了问题。我使用的是内置了apollo+react和express graphQL服务器的reactQL样板(我没有安装apollo服务器--我只是使用了reference express-graphQL包)。我的数据使用_id存储在mongoDB中,但是客户端上的实际数据使用id作为id。
apollo客户端的定义如下:
new ApolloClient(
Object.assign(
{
reduxRootSelector: state => state.apollo,
dataIdFromObject: o => o.id
},
opt
)
);我有一个父组件,它使用'src/graphql/queries/courses.gql‘中的导入课程
@graphql(courses)
export default class CoursesPage extends Component {
constructor(props){
super(props)
this.handleDelete = this.handleDelete.bind(this);
}
handleDelete(event) {
this.props.mutate({ variables: {id: selectedId}}
.catch(err => console.log(err))
}
render() {
return (
{ this.props.data.courses.map(course =>
<CourseDelete selectedId={course.id} key={course.id} />
})
}
)
}
}以及一个子组件,如下所示:
import deleteCoursefrom 'src/graphql/mutations/deleteCourse.gql
@graphql(deleteCourse)
export default class CourseDelete extends Component {
constructor(props){
super(props)
this.handleDelete = this.handleDelete.bind(this);
}
handleDelete(event) {
this.props.mutate({ variables: {id: this.props.selectedId}}
.catch(err => console.log(err))
}
render() {
return (
<button onClick={this.handleDelete}>Button</button>
)
}
}其中deleteCourse.gql:
mutation deleteCourse($id: String!) {
deleteCourse(id: $id) {
id
}
}我的原始查询是用courses.gql编写的:
query courses {
courses {
id
}
}发布于 2017-08-27 15:33:33
阿波罗的dataIdFromObject用于更新缓存中已有的对象。因此,如果您有一条记录和一个ID,并且您根据相同的ID更改了其他数据片段,则监听存储的React组件可以重新呈现。
由于您的deleteCourse突变似乎返回相同的ID,因此它仍然存在于缓存中。你的存储并不知道它需要删除-它只是用返回的任何数据来更新缓存。由于此突变可能返回相同的ID,因此没有任何迹象表明应该将其删除。
相反,您需要指定一个update function (指向官方Apollo文档的链接)来显式删除底层存储数据。
在我的新ReactQL user auth example中,我做了同样的事情(see the pertinent LOC here),在用户登录后‘手动’更新商店。
由于组件最初侦听的是一个“空”用户,所以我不能依赖dataObjectFromId来使缓存无效,因为我一开始没有用户,因此也没有ID。因此,我显式地手动重写了存储状态,这会触发任何侦听组件的重新呈现。
我在YouTube视频中解释了这个概念是上面的用户身份验证的上下文--这是相关的部分:https://youtu.be/s1p4R4rzWUs?t=21m12s
https://stackoverflow.com/questions/45869574
复制相似问题