2

在组件 A 中:

 const getOnClick = useCallback(
    (rec: GenericRec): (() => void) => () => {
      setSelectedRecord(rec);
    },
    [],
  );

在 A 的 B 子组件中:

const openRecord = useCallback(
    (row: Row<Record>) => () => {
      getOnClick({ id: row.original.id, name: row.original.name });
    },
    [getOnClick],
  );

getOnClick不叫

4

1 回答 1

1

您在两个调用中都有一层额外的功能useCallback。与 不同useMemouseCallback直接接受它应该记忆的回调,而不是构建回调的函数。

所以:

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>

于 2020-08-26T11:31:20.377 回答