我有一個包含幾層子組件的表單。表單的狀態保持在最高級別,而我向下傳遞了作為更新最高級別的道具的函數。唯一的問題是,當表單變得很大(您可以動態添加問題)時,每個單個組件都會在其中一個更新時重新加載。這是我的代碼的簡化版本(或codesandbox:https : //codesandbox.io/s/636xwz3rr ):const App = () => { return <Form />;}const initialForm = { id: 1, sections: [ { ordinal: 1, name: "Section Number One", questions: [ { ordinal: 1, text: "Who?", response: "" }, { ordinal: 2, text: "What?", response: "" }, { ordinal: 3, text: "Where?", response: "" } ] }, { ordinal: 2, name: "Numero dos", questions: [ { ordinal: 1, text: "Who?", response: "" }, { ordinal: 2, text: "What?", response: "" }, { ordinal: 3, text: "Where?", response: "" } ] } ]};const Form = () => { const [form, setForm] = useState(initialForm); const updateSection = (idx, value) => { const { sections } = form; sections[idx] = value; setForm({ ...form, sections }); }; return ( <> {form.sections.map((section, idx) => ( <Section key={section.ordinal} section={section} updateSection={value => updateSection(idx, value)} /> ))} </> );};const Section = props => { const { section, updateSection } = props; const updateQuestion = (idx, value) => { const { questions } = section; questions[idx] = value; updateSection({ ...section, questions }); }; console.log(`Rendered section "${section.name}"`); return ( <> <div style={{ fontSize: 18, fontWeight: "bold", margin: "24px 0" }}> Section name: <input type="text" value={section.name} onChange={e => updateSection({ ...section, name: e.target.value })} /> /> ))} </div> </> );};我已經嘗試過使用useMemo和useCallback,但是我不知道如何使它工作。問題是傳遞函數以更新其父級。我無法弄清楚如何在每次表單更新時不對其進行更新。我無法在任何地方在線找到解決方案。也許我在尋找錯誤的東西。感謝您提供的任何幫助!
防止在功能道具更新時重新呈現
慕田峪7331174
2021-05-12 14:09:36