父组件
父组件包含在更改时将状态设置为“本地”的输入,以及在单击时获取此“本地”状态的值并将其设置为“sendLocal”的按钮
功能
changehandler :触发输入类型更改。
sendLocalValue :将“本地”值放入“sendLocal”变量中,单击按钮时触发。
sendValue :这个带有依赖“sendLocal”的记忆函数作为子组件中的道具传递,一旦孩子被渲染,就会触发。
import React, { useState, useCallback } from "react"; import ChildComponent from "./ChildComponent"; function ParentComponent() { const [local, setLocal] = useState(); const [sendLocal, setsendLocal] = useState(); const changehandler = (e) => { console.log("parent"); setLocal(e.target.value); }; const sendLocalValue = () => { setsendLocal(local); }; const sendValue = useCallback(() => { return sendLocal; }, [sendLocal]); return ( <> <input type="text" onChange={changehandler} defaultValue={local} /> <button onClick={sendLocalValue}>send</button> <ChildComponent getValue={sendValue} /> </> ); } export default ParentComponent;
子组件
getValue prop 调用 parent 的memoized "sendValue" 函数,该函数返回 sendLocal 的值。
问题
一切正常,子组件仅在单击按钮时“sendLocal”值发生变化时呈现,但如果我删除子组件中的 React.memo(),即使使用了 useCallback(),组件在输入类型上的呈现也会发生变化,为什么?
import React, { useEffect, useState } from "react";
function ChildComponent({ getValue }) {
console.log("child");
return <div>child's {getValue()}</div>;
}
export default React.memo(ChildComponent);