Javascript 反应-我可以';我不能更新我的功能
我想更新我的回调函数:Javascript 反应-我可以';我不能更新我的功能,javascript,reactjs,usecallback,Javascript,Reactjs,Usecallback,我想更新我的回调函数: const getSchema = React.useCallback( () => { const schema = twSchema( labels, isInitialWarehouseActive ? initialWarehouse.id : undefined, operationTypeDisabled ? initi
const getSchema = React.useCallback(
() => {
const schema = twSchema(
labels,
isInitialWarehouseActive ? initialWarehouse.id : undefined,
operationTypeDisabled ? initialWarehouse.operation_type : undefined
);
schema.addValidator((model, _schema) => {
if (model.dateRangeMode && (!model.timeRangeMode || model.hasRampHours) && !model.dateInpu.to) {
_schema.setModelError('dateInput.to', labels.fieldIsRequired);
...
...
});
return schema;
},
[initialStore]
);
其中,twSchema:
const twSchema = (labels, initialStoreId, storeOperationType) => new Schema({...
以及mygetSchema的用例:
<Form
key="time-window-form"
ctx="time-window-form"
eventsEmitter={eventsEmitter}
model={model}
onError={onError}
onSubmit={(data) => {
...
}).then(() => {
...
})
.catch(hint => displayMessageAndHighlightValidatedComponent(hint));
}}
schema={getSchema()}
>
问题是为什么?为什么我不能更新我的对象/函数?我必须删除useCallback
才能动态添加验证器…如果我理解正确,每次对getSchema的新调用都会生成一个新对象,对吗?请尝试显式定义每个依赖项,而不仅仅是initialStore。与标签一样,isInitialWarehouseActive、operationTypeDisabled、initialWarehouseYes您是对的-函数twSchema()每次都创建新的模式对象!我认为useCallback可能以不同的方式工作,但没有什么神奇之处——每次创建新对象:)谢谢:)使用useCallback
的动机是为了提高性能。只要第二个参数的值不变,它每次都返回相同的实例。如果你的条件设置不正确,记忆可能会很挑剔。除非您需要性能优势,否则不要使用它(您通常不需要)
const displayMessageAndHighlightValidatedComponent = (hint) => {
getSchema().addValidator((model, schema) => {
//this code is not executed!!!
console.log(schema);
console.log('SCHEMA');
schema.setModelError('dateInputField', labels.createNextTimeWindow);
});
return onFailed();
};