1

我被困在一个 thunk 函数的使用中,我需要更好地理解它是如何工作的。

不起作用的代码:

const fields = {
    id: {
        type: new GraphQLNonNull(GraphQLID),
        resolve: (obj) => dbIdToNodeId(obj._id, "History")
    },
    timestamp: {
        type: GraphQLLong
    },
    objectId: {
        type: GraphQLString
    },
    user: {
        type: require('../User/connections').default,
        args: connectionArgs,
        resolve: (source, args) => {
            return UserModel.findOne({ id: source.id }).exec();
        }
    },
    action: {
        type: new GraphQLNonNull(GraphQLString)
    }
};

export const HistoryType = new GraphQLObjectType({
    name: 'History',
    description: 'History',
    interfaces: () => [NodeInterface],
    isTypeOf: (value) => value instanceof HistoryModel,
    fields: () => (fields)
});

有效的代码:

export const HistoryType = new GraphQLObjectType({
    name: 'History',
    description: 'History',
    interfaces: () => [NodeInterface],
    isTypeOf: (value) => value instanceof HistoryModel,
    fields: () => ({
    id: {
        type: new GraphQLNonNull(GraphQLID),
        resolve: (obj) => dbIdToNodeId(obj._id, "History")
    },
    timestamp: {
        type: GraphQLLong
    },
    objectId: {
        type: GraphQLString
    },
    user: {
        type: require('../User/connections').default,
        args: connectionArgs,
        resolve: (source, args) => {
            return UserModel.findOne({ id: source.id }).exec();
        }
    },
    action: {
        type: new GraphQLNonNull(GraphQLString)
    }
})
});

从我“对 JavaScript thunk 不太熟练”的角度来看,两个代码是相同的,但它们并不是只有第二个有效,所以:

a) 为什么代码的行为不一样?为什么将 thunk 内容存储在函数 ( fields) 中会使其行为不同?

b)我的fields变量在代码序列中使用,所以有没有办法让 thunk 工作,将其对象保存在单独的变量中,如代码 1(实际上是对代码 1 的修复,保留field变量)?

4

0 回答 0