我阅读了继电器官方文档并以其为例。
现在,为了练习,我稍微改变一下它。我用useQueryLoader
代替load query
但结果是,Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
我认为这与loadRepoQuery()部分有关,但没有它,TypeError: null is not an object (evaluating 'preloadedQuery.fetchKey')
发生。
我想这是由于我的误解。请帮帮我。
// App.js
import './App.css';
import graphql from 'babel-plugin-relay/macro';
import {
usePreloadedQuery,
useQueryLoader,
} from 'react-relay/hooks';
// Define a query
const RepositoryNameQuery = graphql`
query AppRepositoryNameQuery {
repository(owner: "facebook", name: "react") {
name
}
}
`;
function RepoRenderer() {
const [repoQueryRef, loadRepoQuery] = useQueryLoader(RepositoryNameQuery);
loadRepoQuery();
return (
<Repo preloadedQuery={repoQueryRef}/>
)
}
function Repo(props) {
const data = usePreloadedQuery(RepositoryNameQuery, props.preloadedQuery);
return (
<div className="App">
<header className="App-header">
<p>{data.repository.name}</p>
</header>
</div>
);
}
export default function App() {
return (
<RepoRenderer/>
);
}
//
import React, { Suspense } from 'react';
import ReactDOM from 'react-dom';
import { RelayEnvironmentProvider } from 'react-relay';
import relayEnvironment from './relayEnvironment';
import App from './App';
import './index.css';
ReactDOM.render(
<React.StrictMode>
<RelayEnvironmentProvider environment={relayEnvironment}>
<Suspense fallback={'Loading...'}>
<App/>
</Suspense>
</RelayEnvironmentProvider>
</React.StrictMode>,
document.getElementById('root')
);
我算是解决了这个问题。下面的代码片段适合像我这样的新手。
看这个
// index.js
ReactDOM.render(
<RelayEnvironmentProvider environment={relayEnvironment}>
<Suspense fallback={'Loading...'}>
<App />
</Suspense>
</RelayEnvironmentProvider>,
document.getElementById('root')
);
//app.js
import React ,{ useCallback } from 'react';
import './App.css';
import graphql from 'babel-plugin-relay/macro';
import {
usePreloadedQuery,
useQueryLoader,
} from 'react-relay/hooks';
// Define a query
const RepositoryNameQuery = graphql`
query AppRepositoryNameQuery {
repository(owner: "yujong-lee", name: "taggy") {
name
}
}
`;
function Repo({queryRef, refetch}) {
const data = usePreloadedQuery(RepositoryNameQuery, queryRef);
return (
<div className="App">
<header className="App-header">
<p>{data.repository.name}</p>
</header>
</div>
);
}
function App() {
const [repoQueryRef, loadRepoQuery] = useQueryLoader(RepositoryNameQuery);
const refetch = useCallback(() => {
loadRepoQuery();
}, [loadRepoQuery])
if(repoQueryRef !== null) {
return <Repo queryRef={repoQueryRef} refetch={refetch}/>
}
return <button type='button' onClick={() => refetch()}>Fetch</button>
}
export default App;