我正在构建一个React前端,它允许用户从静态查询列表中选择"活动"查询,并展平到要在表格中显示的结果.将GraphQL查询从更高阶组件传递到嵌套子组件的最佳方法是什么?
我见过的大多数文档/解决方案都侧重于将动态条件从组件状态绑定到组件的静态查询,这对我的目的不起作用,因为不同的静态查询具有不同的字段并查询不同的节点类型.
这里的最佳实践/推荐方法是什么?我觉得这不是一个非常独特的用例,但我似乎找不到任何类似的例子.
我使用Apollo-Client/Redux作为我的客户端商店.
以下是组件的粗略轮廓:
class GridViewPage extends React.Component{
constructor(props, context) {
super(props, context);
this.state = {
activeQuery = ... Stores the selected query ...
};
}
render() {
return (
<div className="gridContainer">
...Component here allows users to select a query from active list and saves it/it's ID/Index to the state...
<Panel collapsible>
...Some toolbar components...
</Panel>
...Component here displays the result of the query (Ideally by receiving the query or the result of as a prop?)...
</div>
);
} …Run Code Online (Sandbox Code Playgroud)使用来自我们的 graphql 服务器的数据呈现页面服务器端有错误。
我们的 GraphQL 服务器与多个 API 对话并返回一个由 Apollo UI 处理的 graphQL 响应。
某些 GraphQL 错误不被视为严重错误,我们仍希望使用它来渲染页面。例如
data: {
thing: {
id: "1234"
name: "Thing"
nonCriticalData: null
},
error: {
graphQLErrors: [
path: ['thing', 'nonCriticalData']
]
}
}
Run Code Online (Sandbox Code Playgroud)
根据我们从 Apollo 得到的上述响应,我们仍然希望使用thing. 综观实行getDataFromTree 这里,任何错误都会抛出,没有数据的其余部分。
以下是我们计划如何处理代码的片段:
getDataFromTree(app)
.then(() => {})
.catch(error => {
const content = ReactDOMServer.renderToString(app);
const { data } = client.getInitialState();
console.log("data", data); <-------------- We need data here
console.log("error", error); <———————— errors …Run Code Online (Sandbox Code Playgroud) reactjs graphql server-side-rendering react-apollo apollo-client
假设我有两张表,一张包含产品,另一张包含价格。
在 Graphql 中,查询可能如下所示:
option {
id
price {
id
optionID
price
date
}
description
}
Run Code Online (Sandbox Code Playgroud)
我向用户展示了一个表单(在 React 中),他们可以在其中同时输入产品详细信息和价格。
当他们提交表单时,我需要在“产品”表中创建一个条目,然后在“价格”表中创建一个相关条目。
我对 Graphql 和 React 非常陌生,我发现它的学习曲线很陡峭,并且一直在关注 Apollo 教程和阅读文档,但到目前为止,此任务的解决方案仍然是个谜!
有人能把我从痛苦中解脱出来,给我,或者给我指明方向,处理必要的突变的最简单的例子吗?
给定以下组件:
export function App() {
return withApollo(<BrowserRouter>
<MatchListRouteHandler />
</BrowserRouter>);
}
// MatchListRouteHandler
export const Query = addTypenameToDocument(gql`
query GetMatches {
matches {
id
}
}
`);
export default graphql(Query)(MatchListRouteHandler);
Run Code Online (Sandbox Code Playgroud)
和测试用例:
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
});
Run Code Online (Sandbox Code Playgroud)
当 Jest 尝试运行测试用例时,我收到以下错误:
/home/dan/match-history-analyser/node_modules/jsdom/lib/jsdom/browser/Window.js:148
return idlUtils.wrapperForImpl(idlUtils.implForWrapper(window._document)._location);
^
TypeError: Cannot read property '_location' of null
at Window.get location [as location] (/home/dan/Projects/match-history-analyser/node_modules/jsdom/lib/jsdom/browser/Window.js:148:79)
at Timeout.callback [as _onTimeout] (/home/dan/Projects/match-history-analyser/node_modules/jsdom/lib/jsdom/browser/Window.js:525:40)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
Run Code Online (Sandbox Code Playgroud) 在前端,我使用 ReactJS 并尝试在列表视图中内置过滤选项。列表视图通过发出以下 graphql 查询从 graphql 端点正确获取数据:
query getVideos($filterByBook: ID, $limit: Int!, $after: ID) {
videosQuery(filterByBook: $filterByBook, limit: $limit, after: $after) {
totalCount
edges {
cursor
node {
id
title
ytDefaultThumbnail
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
Run Code Online (Sandbox Code Playgroud)
初始加载$filterByBook变量设置为null,因此查询正确返回所有节点的所有页面(查询返回分页结果)。然后,通过点击过滤器(按书籍过滤),另一个 graphql 查询正在发出,但它总是返回相同的data. 这是过滤组件的代码片段
renderFilters() {
const { listOfBooksWithChapters, refetch } = this.props;
return (
<Row>
<FilterBooks
onBookTitleClickParam={(onBookTitleClickParam) => {
return refetch({
variables: {
limit: 3,
after: 0,
filterByBook: onBookTitleClickParam
}
})
}}
listOfBooksWithChapters={listOfBooksWithChapters} …Run Code Online (Sandbox Code Playgroud) 我正在使用 React Apollo 查询数据存储中的所有记录,以便我可以在搜索过滤器中创建选择。
我使用的重要数据库模型是Report.
一Report有doorType,doorWidth,glass和manufacturer领域。
目前,当查询响应时,我将传递allReports给多个通过数组的哑组件,并仅获取唯一项以制作可选列表,就像这样..
const uniqueItems = []
items.map(i => {
const current = i[itemType]
if (typeof current === 'object') {
if (uniqueItems.filter(o => o.id !== current.id)) {
return uniqueItems.push(current)
}
} else if (!uniqueItems.includes(current)) {
return uniqueItems.push(current)
}
return
})
Run Code Online (Sandbox Code Playgroud)
显然,这段代码并不漂亮,而且有点矫枉过正。
当查询在我的SidebarFilter组件中返回时,我想分派一个动作。这是查询...
const withData = graphql(REPORT_FILTER_QUERY, {
options: ({ isPublished }) => ({
variables: { isPublished }
})
})
const …Run Code Online (Sandbox Code Playgroud) 我想通过新<Query>组件获取数据,但是我不清楚如何进入本地状态进行编辑,直到我准备好再次保存数据,例如完成编辑.
这个答案回答了旧HOC方式的问题,但在进行新组件时保持问题开放: 如何使用graphQL在React/Apollo中设置state()
我正在使用带有响应和阿波罗的graph.cool api。我正在使用graph.cools默认电子邮件传递集成构建身份验证系统。以某种方式登录突变可以完美地工作,但是寄存器突变不能工作。注意:登录和注册突变功能都在同一页面上。没有登录工作注册。
注册功能:
async register(){
await client.mutate({
mutation: gql`
mutation createUser($email: String!, $password: String!){
createUser(
authProvider : {
email: {
email: $email,
password: $password
}
}
) {
id
}
}
`,
variables: {
email: this.state.regEmail,
password: this.state.regPass
},
})
.then(result => { this.props.history.push({
pathname: '/dashboard',
state: { logInfo: [result.data.signinUser.token,
result.data.signinUser.user.id] }
});
})
.catch(error => { console.log(error)});
}
Run Code Online (Sandbox Code Playgroud)
登录功能:
async login(){
await client.mutate({
mutation: gql`
mutation signinUser($email: String!, $password: String!){
signinUser(
email: { email: $email, password: $password }
) …Run Code Online (Sandbox Code Playgroud) 我有一个组件,用于显示从Spotify API返回的搜索数据。但是,每次更新状态时,UI都会闪烁:
<DebounceInput
debounceTimeout={300}
onChange={handleChange}
/>
Run Code Online (Sandbox Code Playgroud)
钩:
const [searchResults, setSearchResults] = useState(null)
Run Code Online (Sandbox Code Playgroud)
带Apollo的API调用:
const searchSpotify = async (query) => {
const result = await props.client.query({
query: SearchTracks,
variables: {
query
}
})
const tracks = result.data.searchedTracks
setSearchResults(tracks)
}
Run Code Online (Sandbox Code Playgroud)
渲染:
{searchResults &&
<div className="search-results">
{searchResults.map((song) => (
<SongInfo key={song.id} {...song} />
))}
</div>
}
Run Code Online (Sandbox Code Playgroud)
我注意到它仅在第一次加载时发生。例如,如果我再次键入查询,它将显示而不会闪烁。有没有更好的方法来实现此目的,以使UI不会闪烁?
我已经包装了Query和Mutations,所以我可以全局处理每个操作都需要进行的重复操作Query, Mutation。在查询中,我转换数据,所以我不必担心所有nodes, edges, etc
我正在使用react-adopt将所有组件query和mutations组件包装回视图层的一个渲染道具。
<ApolloQuery>export const ApolloQuery = ({
query: query,
render,
}) => {
return (
<Query query={query}>
{({ data }) => {
return (
<Fragment>
render(data)
</Fragment>
)
}}
</Query>
)
}
Run Code Online (Sandbox Code Playgroud)
export default externalProps => {
return (
<QueryContainer {...externalProps}>
{({ someQueryData, aMutation }) => { //react-adopt render props
const { nestedData } = new apolloClass(someQueryData).start()
return (
<Grid container spacing={16}>
{nestedData.map((ticket, index) => …Run Code Online (Sandbox Code Playgroud) react-apollo ×10
graphql ×7
reactjs ×7
javascript ×4
apollo ×1
react-adopt ×1
react-hooks ×1
react-native ×1
react-redux ×1
redux ×1