文件例:
import type {AppQueryType} from AppQueryType.graphql ;
const React = require( React );
const {graphql, useQueryLoader, usePreloadedQuery} = require( react-relay );
const AppQuery = graphql`
query AppQuery($id: ID!) {
user(id: $id) {
name
}
}
`;
type Props = {
initialQueryRef: PreloadedQuery<AppQueryType>,
};
function NameLoader(props) {
const [queryReference, loadQuery] = useQueryLoader(
AppQuery,
props.initialQueryRef, /* e.g. provided by router */
);
return (<>
<Button
onClick={() => loadQuery({id: 4 })}
disabled={queryReference != null}
>
Reveal your name!
</Button>
<Suspense fallback="Loading...">
{queryReference != null
? <NameDisplay queryReference={queryReference} />
: null
}
</Suspense>
</>);
}
function NameDisplay({ queryReference }) {
const data = usePreloadedQuery(AppQuery, queryReference);
return <h1>{data.user?.name}</h1>;
}
过于复杂。 首先,我不想将初步组成部分分成<代码>。 姓名:Loader和NameDisplay
,这只是因为它方便了Relay。 其次,即使我有儿童部分,我也不想把<条码>上载的Quedery列入<条码>,因为它是Relay和简单反应部分的严格范围(即用其他内容取代Relay,将需要编辑所有组成部分,如<条码>。 相反,我想通过<条码>props通过正常数据,例如<条码>用户/代码>。
理想的法典如下:
import type {AppQueryType} from AppQueryType.graphql ;
const React = require( React );
const {graphql, useQueryLoader, usePreloadedQuery} = require( react-relay );
const AppQuery = graphql`
query AppQuery($id: ID!) {
user(id: $id) {
name
}
}
`;
function NameLoader(props) {
const rawUser = useMagic(AppQuery);
const [ user, setUser ] = toLocalState(rawUser);
return (<>
<Button
onClick={() => loadQuery({id: 4 })}
disabled={queryReference != null}
>
Reveal your name!
</Button>
<h1>{user.name}</h1>;
</>);
}
我的理解是,数据计算是同步的,但并不意味着真实情况在唯一的正确解决办法中表明了这一点。
From the const [ user, setUser ] = toLocalState(rawUser);
line, I want to work with the user
variable as with normal local state. In this example, I don t care that local changes with user
will not reflect on user
at server side - when I ll be ready for reflecting, I ll invoke the appropriate mutation.
What will be instead of useMagic
and toLocalState
?