我需要一些帮助,使用Apollo 2.1中的新Query和Mutation组件,特别是有多个查询和突变。
我有以下问题:
你应该嵌套它们。从docs看到这个例子:
const NumbersWithData = () => (
<Query query={QueryOne}>
{({ loading: loadingOne, data: { one } }) => (
<Query query={QueryTwo}>
{({ loading: loadingTwo, data: { two }}) => {
if (loadingOne || loadingTwo) return <span>loading...</span>
return <h3>{one} is less than {two}</h3>
}}
</Query>
)}
</Query>
);
为了帮助保持嵌套的可管理性,您可以检查react-adopt。他们有一个Apollo ToDo应用程序示例,它们结合了Query和多个Mutations。
为此,react-apollo
出口compose
功能。使用此功能,您可以一次性使用多个组件增强器。包括多个graphql(),甚至是Redux connect()增强器。
import { Mutation, compose, graphql } from "react-apollo";
class AddTweet extends Component {
....
....
....
}
export default compose(
graphql(GET_AUTHORS, { name: "getAuthors" }),
graphql(ADD_TWEET, { name: "addTweet" }),
connect(...), // incase you are using Redux
)(AddTweet);
一个重要的注意事项是,compose()
首先执行最后一个增强器,然后通过增强器列表向后执行。
还有一件事可以说你现在正在使用this.props.data
,你会得到undefined
。只是console.log(this.props)
,你会看到现在道具发生了什么。您现在将拥有两个属性getAuthors
和addTweet
。所以现在它将是this.props.name-in-compose.name-of-type-in-typeDefs
即this.props.getAuthors.getUsers
。我花了一点时间才弄明白。
在我看来,
props
)传递给它并执行该请求。compose
...
@compose(
graphql(GET_FEEDS_QUERY, {name : 'getFeeds'}),
graphql(CREATE_NEW_POST, {name: "createNewPost"}),
graphql(LIKE_POST_MUTATION, { name: "unlikePostMutation"}),
...
)
class HomeScreen extends Component {
...
}
我写了一篇关于如何在同一个Component上组合Mutation和Query的Medium Post。这是帖子的片段
// other import
import {Query} from “Apollo-graphql”; // new Query Component
import gql from "graphql-tag";
import { graphql } from "react-apollo";
import UserComponent from '../component/UserComponent'; // any component to display query result
const GET_ALL_USER = gql`
{
allUsers: {
firstname,
lastname,
username,
# other information
}
}
`
const UPDATE_USER_STATUS = gql`
mutation UpdateUserStatus($userID: ID!, $status: Int!){
updateUserState(userID: $userID, status: $status){
firstname,
lastname
username
# other information
}
}
`
ExampleComponent extends React.Component{
onEditInformation = async (user) => {
const response = await mutate({
variables: {userID: user}
})
}
render(){
return(
<Query query={GET_ALL_USER}>
{({data: { allUsers }}) => {
return allusers.map(user => {
return (
<UserComponent
user={user}
onEdit={() => this.onEditInformation(user)}
/>
)
})
}}
</Query>
)
}
}
export default graphql(UPDATE_USER_STATUS)(ExampleComponent);