javascript - 当 useState 钩子的状态发生变化时反应不重新渲染(Object.is = false)
问题描述
我有一个使用钩子的 React 功能组件。该组件基于两个孩子:
- 第一个是列出数据(时间序列)的表格,可以在其中选择行。
- 我打算在其中绘制上表选定行的图表。
我面临的问题是,当我选择新行时,图表部分会更新。但不是当我取消选择行时。
要渲染的组件如下:
const chart = (isChartLoading ? <div>Loading ...</div> :
<TSChart
initialRange={initialRange}
channels={channels}
style={style}
/>);
return (
<div> {
error ? (<div className="App-error"><p>{error}</p></div>) :
(<div style={{maxWidth: '100%'}}>
<TSTable
tsList={tsList}
onSelectTableRow={onSelectTableRow}
/>
</div>)}
{chart}
</div>
)
这是我正在使用的钩子:
const [tsList, setTsList] = useState([]);
const [channels, setChannels] = useState({});
const [isChartLoading, setIsChartLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
function fetchTsList() {
axios.get(urlList)
.then(result => setTsList(result.data))
.catch(() => setError('Impossible to get TS list'));
}
fetchTsList()
}, []);
管理行选择的代码如下:
function onSelectTableRow(rows) {
const currentChannelsNames = Object.keys(channels);
const selectedChannelsNames = rows.map(row => row.name);
// Remove deselected channels from charted channels
const deselectedChannelsNames = currentChannelsNames.filter(x => !selectedChannelsNames.includes(x));
function removeDeselectedChannels(channels) {
const updatedChannels = {...channels};
deselectedChannelsNames.forEach((name) => {
delete updatedChannels[name];
removeGraphStyleArray(name);
});
style = styler(style_array);
console.log('channels in removeDeselectedChannels', channels);
console.log('updatedChannels in removeDeselectedChannels', updatedChannels);
console.log(Object.is(channels, updatedChannels));
return updatedChannels;
}
if (deselectedChannelsNames.length !== 0) setChannels(removeDeselectedChannels);
// Manage additional channels
const newChannelsNames = selectedChannelsNames.filter(x => !currentChannelsNames.includes(x));
// Load the additional channel(s)
if (newChannelsNames.length !== 0) newChannelsNames.forEach(fetchTSValues);
}
如您所见,我使用 traces ( console.log
) 来跟踪channels
状态的变化。当我取消选择一行时,channels
状态确实在改变,如下图所示:
channels in removeDeselectedChannels {demo-temperature-4: {…}}
updatedChannels in removeDeselectedChannels {}
false
并且Object.is
确实是在说channels
更新的状态与以前的状态不同。但是,TSChart
组件不会重新渲染,而是保留先前选择的时间序列的显示。
我错过了什么的任何线索?
解决方案
推荐阅读
- firebase - 错误仅在第一次调用时出现,一旦屏幕再次打开,错误就会消失,
- python - 如何在 ndarray 上使用 .cov() 函数?
- oracle - 在 Oracle Apex 版本 18.2 中,“带有自动完成功能的文本”显示所有数据,但滚动条会导致窗口关闭
- python - discord.py 无法更改频道名称
- mysql - 扩展统计 mysql 和 tcl
- javascript - tar 并将多个文件上传到 Node.js 中的 S3
- python - 谷歌云,数据库服务器
- ssl - Cloudflare ssl 证书不在代理服务器下
- sqlite - 在 Flutter 中修改现有数据库后出现 OpenDatabase 错误
- c++ - OpenCV - 如何将一个 RGB 图像除以另一个?