我第一次尝试使用React (),以防止不必要地为注释重新呈现TextInputs。成功地防止了这些重呈现,页面性能略有提高(在实际示例中可能有数百个注释)。
然而,在按下重置按钮后,会发生一些奇怪的事情。更改以前没有编辑过的注释将导致旧注释在其他TextInputs中重新出现。
我的问题是:为什么旧的音符会以这种方式重现,我如何在保持优化渲染的同时绕过它呢?
import React, { useState } from 'react';
export const ReRendering = () => {
const defaultNotes = [
{id: '0155', note: ''},
{id: '0197', note: ''},
{id: '0045', note: ''},
{id: '0244', note: ''},
{id: '0162', note: ''},
];
const [notes, setNotes] = useState(defaultNotes);
function updateNote(e) {
let newNotes = [];
notes.map(r => {
if(e.target.name === r.id) {
r.note = e.target.value;
}
newNotes.push(Object.assign(r));
});
setNotes(newNotes);
}
return (
<div className={'mt-5'}>
<h3>Notes</h3>
<table className={'table table-sm'}>
<thead>
<tr>
<th>ID</th>
<th>Note</th>
</tr>
</thead>
<tbody>
{notes.map(note => {
return (
<tr key={note.id}>
<td>
<input type={'text'}
disabled
className={'form-control border-0'}
value={note.id}
/>
</td>
<td>
<MemoTextInput
value={note.note}
name={note.id}
handleChange={updateNote}
/>
</td>
</tr>
)
})}
</tbody>
</table>
<button onClick={() => setNotes(defaultNotes)}>Revert</button>
</div>
)
};
const TextInput = ({value, handleChange, name}) => {
return (
<input
type={'text'}
className={'form-control'}
value={value}
onChange={handleChange}
name={name}
/>
)
};
function areEqual(prevProps, nextProps) {
return prevProps.value === nextProps.value;
}
const MemoTextInput = React.memo(TextInput, areEqual);发布于 2019-12-13 11:51:19
这个问题与updateNote()函数有关。没有重新呈现的TextInputs上有一个旧版本的updateNote(),因此也有一个旧版本的notes。
对于updateNotes()的这个修订版,它可以正常工作。
function updateNote({target}){
setNotes(oldNotes => {
const newNotes = [...oldNotes];
newNotes.filter(n => n.id === target.name)[0] = {...oldNotes.filter(n => n.id === target.name)[0]};
newNotes.filter(n => n.id === target.name)[0].note = target.value;
return newNotes;
})
}发布于 2019-12-12 13:56:58
当分配r.note = e.target.value;时,您正在更改原始状态(默认注释),这可能会对其他一切产生不良影响。
const newNotes = notes.map(r => {
if (e.target.name === r.id) {
return { ...r, note: e.target.value };
} else {
// no need to copy object here, it would only make your performance worse
return r;
}
});https://stackoverflow.com/questions/59306132
复制相似问题