gpt4 book ai didi

reactjs - 调用 store.writeQuery() 后组件不会重新呈现

转载 作者:行者123 更新时间:2023-12-04 17:33:45 25 4
gpt4 key购买 nike

所以我正在关注 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() 并期望被点赞的链接将重新呈现以显示新的票数。我还记录了传入的数据对象,以确保它已更新,而且确实已更新。但是没有重新渲染。有什么问题吗?

最佳答案

将更多信息添加到 apolloClient dataIdFromObject:documentation

const apolloClient = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
dataIdFromObject: o => o.id
})

关于reactjs - 调用 store.writeQuery() 后组件不会重新呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57540204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com