我正在使用 React 测试 Apollo Graphql,并尝试使用带有嵌套对象的 Apollo Graphql 更新本地状态。我遇到了一个问题。数据返回一个null
值,甚至不返回我设置为默认值的值。我看到的唯一警告是Missing field __typename
. 我不确定我遗漏了什么,或者这不是您使用 Graphql 或 Apollo 问题正确设置嵌套值的方式。我有一个代码沙箱,其中包含我正在尝试做的示例https://codesandbox.io/embed/throbbing-river-xwe2y
index.js
import React from "react";
import ReactDOM from "react-dom";
import ApolloClient from "apollo-boost";
import { ApolloProvider } from "@apollo/react-hooks";
import App from "./App";
import "./styles.css";
const client = new ApolloClient({
clientState: {
defaults: {
name: {
firstName: "Michael",
lastName: "Jordan"
}
},
resolvers: {},
typeDefs: `
type Query {
name: FullName
}
type FullName {
firsName: String
lastName: String
}
`
}
});
client.writeData({
data: {
name: {
firstName: "Kobe",
lastName: "Bryant"
}
}
});
const rootElement = document.getElementById("root");
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
rootElement
);
应用程序.js
import React from "react";
import Name from "./Name";
import { useApolloClient } from "@apollo/react-hooks";
function App() {
const client = useApolloClient();
client.writeData({
data: {
name: {
firstName: "Lebron",
lastName: "James"
}
}
});
return (
<div>
<Name />
</div>
);
}
export default App;
名称.js
import React from "react";
import { NAME } from "./Queries";
import { useApolloClient } from "@apollo/react-hooks";
const Name = async props => {
const client = useApolloClient();
const { loading, data } = await client.query({ query: NAME });
console.log(data);
return <div>Hello {data.name.firstName}</div>;
};
export default Name;
QUERIES.js
import gql from "graphql-tag";
export const GET_NAME = gql`
{
name @client {
firstName
lastName
}
}
`;