![](/img/trans.png)
[英]How to update a state without re-rendering using useState hook
[英]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.