您在两个调用中都有一层额外的功能useCallback
。与 不同useMemo
,useCallback
直接接受它应该记忆的回调,而不是构建回调的函数。
所以:
const getOnClick = useCallback(
(rec: GenericRec): (() => void) => {
// ^−−−− no () => here
console.log("getOnClick");
setSelectedRecord(rec);
},
[],
);
const openRecord = useCallback(
(row: Row<Record>) =>
// ^−−−− no () => here
getOnClick({ id: row.original.id, name: row.original.name })
,
[getOnClick],
);
实时示例(TypeScript 类型注释被注释掉):
const { useState, useCallback } = React;
function Example() {
const [selectedRecord, setSelectedRecord] = useState(null);
const getOnClick = useCallback(
(rec/*: GenericRec*/)/*: (() => void)*/ => {
console.log("getOnClick");
setSelectedRecord(rec);
},
[]/*,*/
);
const openRecord = useCallback(
(row/*: Row<Record>*/) =>
// ^−−−− no () => here
getOnClick({ id: row.original.id, name: row.original.name })
,
[getOnClick]/*,*/
);
const addRecord =() => {
console.log("addRecord");
openRecord({
original: {
id: 1,
name: "The record"
}
});
};
return (
<div>
<input type="button" value="Click Me" onClick={addRecord} disabled={!!selectedRecord} />
{selectedRecord && <span>Selected record: "{selectedRecord.name}" ({selectedRecord.id})</span>}
{!selectedRecord && <em>No record selected</em>}
</div>
);
}
ReactDOM.render(<Example/>, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>