简体   繁体   English

如何从GraphQL查询中获取字段值?

[英]How can I get the field value from GraphQL query?

I have the Apollo Client that query the value from MongoDB collection then I try to fetch the value from "findOne". 我有Apollo客户端,它从MongoDB集合中查询值,然后尝试从“ findOne”中获取值。 When I try to get the value (for example "eventname", it alert that "cannot read property 'eventname' of undefined". 当我尝试获取值时(例如“ eventname”,它会警告“无法读取未定义的属性'eventname'”)。

This is the schema and resolver. 这是架构和解析器。

type Event {
    _id: ID!
    eventname: String!
    remark: String
    username: String
    createdAt: Date 
    updatedAt: Date
    registers: [Register]
}

type Query {
    eventList(_id: ID): Event
}
    eventList: async(parents, args, { Event }) => {
        const eventList = Event.findOne({ _id: args._id });

        if (!eventList) {
            throw new Error('No such event found');
        }

        return eventList;
    },

The query from client: 来自客户端的查询:

class RegistersIndex extends Component {

    render() { 
        const { data: {loading, error, eventList}, match } = this.props;
        console.log(eventList.eventname);
...
...
export const eventsListQuery = gql`
    query EventsListQuery ($eventid: ID!) {
    eventList (_id: $eventid) {
        _id
            eventname
            remark
            username
            createdAt
            updatedAt
    }
  }
`;

export default graphql(eventsListQuery, {
    options: (props) => ({
        variables: { eventid: props.match.params._eventid },
    })
})(RegistersIndex);

在此处输入图片说明

在此处输入图片说明

It could be because eventList would be undefined while the data is being fetched. 可能是因为在获取数据时eventListundefined Add a condition to check whether loading is true so that eventList fields are accessed only after loading is done. 添加条件以检查loading是否为true以便仅在加载完成后才访问eventList字段。

render() { 
    const { data: {loading, error, eventList}, match } = this.props;
    if (loading) return <div>Loading...</div>
    console.log(eventList.eventname);
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM