首页 > 解决方案 > 当 useState 钩子的状态发生变化时反应不重新渲染(Object.is = false)

问题描述

我有一个使用钩子的 React 功能组件。该组件基于两个孩子:

  1. 第一个是列出数据(时间序列)的表格,可以在其中选择行。
  2. 我打算在其中绘制上表选定行的图表。

我面临的问题是,当我选择新行时,图表部分会更新。但不是当我取消选择行时。

要渲染的组件如下:

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组件不会重新渲染,而是保留先前选择的时间序列的显示。

我错过了什么的任何线索?

标签: javascriptreactjsreact-hooks

解决方案


推荐阅读