【发布时间】:2019-12-23 16:44:08
【问题描述】:
所以我正在关注https://www.howtographql.com/react-apollo/6-more-mutations-and-updating-the-store/ 的 graphql + apollo 教程,并且我有一堆“链接”组件,当被投票时应该显示新的投票数。到目前为止,它在被投票时不会重新渲染,我必须刷新页面。
我尝试通过使用更新的数据调用 store.writeQuery() 来做到这一点。我查了一下,我传入的数据对象确实和旧的不一样:
这是我的初始设置:
import { ApolloProvider } from "react-apollo";
import { ApolloClient } from "apollo-client";
import { createHttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory"
import { setContext } from "apollo-link-context";
import App from './components/App';
import {AUTH_TOKEN} from "./constants.js";
const authLink = setContext((_, { headers }) =>
{
const token = localStorage.getItem(AUTH_TOKEN);
return {
headers: {
...headers,
authorization: (token ? "Bearer " + token : ""),
}
}
});
const httpLink = createHttpLink({
uri: "http://localhost:4000"
});
const apolloClient = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
})
这是突变组件:
<Mutation
mutation={VOTE_MUTATION}
variables={{id: this.props.link.id}}
update={(store, { data: { upVote } }) =>
{
const data = store.readQuery({ query: FEED_QUERY });
const votedLink = data.feed.links.find(link => link.id === this.props.link.id);
votedLink.votes = upVote.link.votes;
console.log(data);
store.writeQuery({
query: FEED_QUERY,
data,
});
} }
>
{
mutationCallback =>
(<div className="ml1 gray f11" style={{cursor: "pointer"}} onClick={mutationCallback}>
▲
</div>)
}
</Mutation>
这是获取所有链接的查询:
const FEED_QUERY = gql`
{
feed
{
links
{
id url description createdAt
createdBy{
name email
}
votes{
id
}
}
}
}
`;
我调用 store.readQuery() 和 store.writeQuery() 并期望被投票的链接将重新呈现以显示新的投票数。我还记录了传入的数据对象,以确保它已经更新,并且已经更新。但没有重新渲染。有什么问题?
【问题讨论】: