我认为 React 只是重新加载我需要的东西 - 在我的例子中它看起来不同或者我做错了什么。
我有员工表。对于一天中的每个员工,我可以设置工作开始和结束时间。像这样:
const ScheduleRow = React.memo((props) => {
return (
<tr>
// number of row - doesn't matter
<th className="text-center">{ props.no }</th>
{ ["2020-01-01", "2020-01-02", "2020-01-03", "2020-01-04" /* etc */ ].map(
date => { return (
<ScheduleCell date={ date } employee_id={ props.employee_id }/>
)}) }
</tr>
)
})
const ScheduleCell = React.memo((props) => {
const dispatch = useDispatch()
let schedule_id = `${props.employee_id}:${props.date}`
const schedule = useSelector(state => state.schedules)[schedule_id] || null
/* some code here - not changing state */
console.log(props.date)
return (
<td>
<Form.Control type="text" value={schedule?.begin}
onChange={(e) => dispatch({
type: "EDIT_SCHEDULE",
schedule_id: schedule_id,
property: "begin",
value: e.target.value
})}/>
<Form.Control type="text" value={schedule?.cease}
onChange={(e) => dispatch({
type: "EDIT_SCHEDULE",
schedule_id: schedule_id,
property: "cease",
value: e.target.value
})}/>
</td>
)
});
您可以看到我在 Return 之前在 ScheduleCell 中有 console.log() ,它打印正在编辑的日期。我相信,当我更改单元格(例如日期“2020-01-02”)时,我应该在控制台中只看到“2020-01-02”。但是我在 ScheduleRow 中看到数组中的每个日期,这意味着即使我只更改了一个单元格,React 也会修改每个单元格。
我的推理有什么问题以及如何改进它以仅重新加载编辑单元格?
最佳答案
确保添加正确的 key
支持您的<ScheduleCell/>
元素。如果没有这个,React 将不会关联到在重新渲染时应重用相同的组件实例。对于任何渲染 <ScheduleRow/>
都是如此.
const ScheduleRow = React.memo((props) => {
return (
<tr>
<th className="text-center">{ props.no }</th> // number of row - doesn't matter
{ ["2020-01-01", "2020-01-02", "2020-01-03", "2020-01-04" /* etc */ ].map(date => { return (
<ScheduleCell key={ date } date={ date } employee_id={ props.employee_id }/>
)}) }
</tr>
)
})
React.memo
仅当 props 与上次渲染该实例时相同时,才会记住组件实例上下文中的输出。有关其工作原理的更多信息,请阅读 React 的 Reconciliation .
关于javascript - React 重新渲染 - 误解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61807997/