graphql缓存DataIdFromObject不会导致React重新渲染

时间:2018-06-25 05:58:43

标签: reactjs graphql react-apollo

我在一个反应​​组件中定义了两个突变onLikeonSubmit。对于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
});

我期望看到什么?

我希望onSubmitonLike之间的行为是相同的。因此,当我单击任一按钮时,它只应查询一次,而无需重新获取数据。

我看到什么?

onLike可以正常工作。当单击时,它仅发出一个突变,而react组件将立即呈现。

onSubmit将我带到空白页,然后刷新页面后,将显示新数据。我可以使用refetchrefetchQueries: []使其工作,但这并不重要。

1 个答案:

答案 0 :(得分:-1)

onSubmit函数的上下文未绑定,因此您不会阻止默认的表单行为

更改:

<button onClick={this.onSubmit.bind(this)}>Submit</button>

收件人:

<a href="localhost:3001/change_password">{this.state.validMessage}</a>