繁体   English   中英

使用 useState 更新不会在 React 中重新渲染页面

[英]update using useState is not re-rendering the page in React

我有下面的代码,我需要在双击 td 标签时呈现输入字段

const [getTableData, setTableData] = useState(tableData);

//td tag in the HTML table
    {getTableData.map((data, index) => (
                        <tr key={index}>
                            <td>{index + 1}</td>
                            <td onDoubleClick={handleDateDoubleClick} data-key={data.uniqueKey}>
                                {renderDate(data)}
                            </td>
    </tr>
    ))}

// handles double click 
function handleDateDoubleClick(event) {
        let currentRecord = getTableData.find(data => {
            if (+(data.uniqueKey) === +(event.target.dataset.key)) {
                data.readOnlyDate = data.readOnlyDate ? false : true;
                return data;
            }
        })

        setTableData([...getTableData]); // using spread operator but still no luck.
        renderDate(currentRecord); // explicitly calling renderDate method still nothing.
        console.log(JSON.stringify(currentRecord));
    }
//conditionally render the input field.
    const renderDate = (data) => {
        if (data.readOnlyDate) {
            return data.Date
        } else {
            return (
                <FormControl
                    value={data.Date}
                    data-key={data.uniqueKey}
                    onChange={handleDateChange}
                />
            );
        }
    }

在控制台日志中,我可以看到数组已更新,但仍未使用输入字段而不是静态文本重新呈现页面,请确认我是否在这里遗漏了某些内容。

您正在改变现有状态,因此 React 不会重新检查对象的内容:

data.readOnlyDate = data.readOnlyDate ? false : true;

永远不要在 React 中改变状态。 相反,克隆对象。

const index = getTableData.findIndex(data => +(data.uniqueKey) === +(event.target.dataset.key));
const currentRecord = getTableData[index];
const newRecord = { ...currentRecord, readOnlyDate: !currentRecord.readOnlyDate };
setTableData([
  ...getTableData.slice(0, index),
  newRecord,
  ...getTableData.slice(index + 1),
]);
renderDate(newRecord);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM