因此,我正在关注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(),期望更新的链接将重新显示以显示新的投票数。我还记录了传入的数据对象,以确保它已被更新。但是没有重新渲染。怎么了?
答案 0 :(得分:1)
添加到apolloClient dataIdFromObject以获得更多信息,这里:documentation
const apolloClient = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
dataIdFromObject: o => o.id
})