我有类似下面的代码
在这里,我想从回调函数expandSchema调用函数expandUnexpandSchema。如何做到这一点?我可以从expandSchema调用loadSchemaInfo回调函数,但这导致所有代码执行。但是我只希望执行特定的块。
function useSchemaState() {
const [expand, setExpand] = useKeyState('expand', false);
const expandSchema = useCallback(() => {
setExpand((expand) => !expand);
loadSchemaInfo();
}, [setExpand]);
const loadSchemaInfo = useCallback(
async(connectionId, reload) => {
// Some more lines of code
const expanded = {};
expandUnexpandSchema() {
if (data) {
Object.keys(data).forEach((schemaName) => {
expanded[schemaName] = expand;
});
};
}
);
};
预先感谢大家。
更新:
if(data)//通过调用REST API检索此处的数据,如果要再次检索,则将花费大量时间。如果在loadSchemaInfo之外定义expandUnexpandSchema,是否有任何方法可以通过将数据存储在变量中而不会丢失而保留数据?
答案 0 :(得分:0)
您可以简单地在expandUnexpandSchema
上下文之外定义loadSchemaInfo
函数。我不完全知道您的代码的逻辑,但这是一个可能的解决方案:
function useSchemaState() {
const [expand, setExpand] = useKeyState('expand', false);
const expandSchema = useCallback(() => {
setExpand((expand) => !expand);
expandUnexpandSchema(data); // take data from somewhere.. I suppose you have it
}, [setExpand]);
const expandUnexpandSchema = (data) =>
{
const expanded = {};
Object.keys(data).forEach((schemaName) => {
expanded[schemaName] = expand;
});
return expanded;
}
const loadSchemaInfo = useCallback(
async(connectionId, reload) => {
// Some more lines of code
// do something with expanded
const expanded = expandUnexpandSchema(data);
}
);
};
答案 1 :(得分:0)
在loadSchemaInfo之外定义它,并在loadSchemaInfo和expandSchema中调用它,或尝试以下操作:
const expandSchema = useCallback(() => {
setExpand((expand) => !expand);
loadSchemaInfo.expandUnexpandSchema();
}, [setExpand]);
const loadSchemaInfo = useCallback(
async(connectionId, reload) => {
// Some more lines of code
const expanded = {};
expandUnexpandSchema() {
if (data) {
Object.keys(data).forEach((schemaName) => {
expanded[schemaName] = expand;
});
};
}
loadSchemaInfo.expandUnexpandSchema = expandUnexpandSchema;
);
};
基于Javascript call nested function
在功能方面,花括号之间的任何内容都无法通过外部访问,除非可以通过点符号属性分配或return语句进行访问。您可以在外部函数的外部或内部进行赋值,但是无论哪种方式,都需要外部动作,最少要运行一次外部函数。 – Magnus Lind Oxlund 19年6月2日在12:21