我在一个反应组件中定义了两个突变onLike
和onSubmit
。对于onLike
突变,我可以使用带有DataIdFromObject
的缓存来更新数据,而无需使用this.props.data.refetch()
或refetchQueries: []
重新获取数据。但不用于onSubmit
突变。
// --- React组件
onSubmit(e) {
e.preventDefault();
this.props
.addLyricQuery({
variables: {
content: this.state.content,
songId: this.props.params.id,
},
});
}
onLike(id, likes) {
this.props.likeLyricQuery({
variables: { id },
optimisticResponse: {
__typename: "Mutation",
likeLyric: {
id,
__typename: "LyricType",
likes: likes + 1,
},
},
});
}
<button onClick={() => this.onLike(lyric.id, lyric.likes)}>
<button onClick={e => this.onSubmit(e)}>Submit</button>
// ---阿波罗连接
const enhancer = compose(
graphql(fetchSongQuery, {
options: props => ({
variables: {
id: props.params.id,
},
}),
}),
graphql(addLyricQuery, { name: "addLyricQuery" }),
graphql(likeLyricQuery, { name: "likeLyricQuery" })
);
export default enhancer(SongDetail);
//-addLyric查询
import gql from "graphql-tag";
export default gql`
mutation AddLyricToSong($content: String, $songId: ID) {
addLyricToSong(content: $content, songId: $songId) {
id
title
lyrics {
id
content
}
}
}
`;
// ---类似查询
import gql from "graphql-tag";
export default gql`
mutation LikeLyric($id: ID!) {
likeLyric(id: $id) {
id
likes
content
}
}
`;
// ---阿波罗商店
const client = new ApolloClient({
dataIdFromObject: o => o.id
});
我期望看到什么?
我希望onSubmit
和onLike
之间的行为是相同的。因此,当我单击任一按钮时,它只应查询一次,而无需重新获取数据。
我看到什么?
onLike
可以正常工作。当单击时,它仅发出一个突变,而react组件将立即呈现。
onSubmit
将我带到空白页,然后刷新页面后,将显示新数据。我可以使用refetch
或refetchQueries: []
使其工作,但这并不重要。
答案 0 :(得分:-1)
onSubmit函数的上下文未绑定,因此您不会阻止默认的表单行为
更改:
<button onClick={this.onSubmit.bind(this)}>Submit</button>
收件人:
<a href="localhost:3001/change_password">{this.state.validMessage}</a>