javascript - React 重新渲染 - 误解

标签 javascript node.js reactjs redux virtual-dom

我认为 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/

相关文章:

javascript - jQuery 有多个点击事件

javascript - 如果使用 Angular js 与 ng-repeat 一起使用,则调用一次函数

html - 通过 app.post 呈现的页面出现 `Confirm Form Resubmission` 问题( '/' ,在expressjs中

java - 如何将 jarsigner 添加到 PATH

reactjs - tabIndex 专注于 anchor 标签内的内部 React 组件

javascript - 如何将我的方法重写为 async/await?

javascript - 在页面上的几个 Bootstrap 弹出窗口中,我需要一个可滚动的

javascript - 将多个抓取数据存储在一个数组中

javascript - typescript 导入返回 "Cannot find module"

javascript - CoffeeScript - 将 SublimeText 配置为简单的 IDE