我有Apollo客户端查询MongoDB集合中的值然后我尝试从“findOne”获取值。当我尝试获取值时(例如“eventname”,它会警告“无法读取未定义的属性'eventname'。”
这是架构和解析器。
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;
},
来自客户的查询:
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);
答案 0 :(得分:0)
可能是因为eventList
在获取数据时会undefined
。添加条件以检查loading
是否为true
,以便仅在加载完成后访问eventList
字段。
render() {
const { data: {loading, error, eventList}, match } = this.props;
if (loading) return <div>Loading...</div>
console.log(eventList.eventname);
...