在useState挂钩状态更改时,React不重新呈现(Object.is = false)

时间:2020-02-27 08:17:53

标签: javascript reactjs react-hooks

我有一个使用钩子的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);
}

如您所见,我正在使用跟踪(console.log)来跟踪channels状态的变化。当我取消选择一行时,channels状态确实在变化,如以下跟踪所示:

channels in removeDeselectedChannels {demo-temperature-4: {…}}
updatedChannels in removeDeselectedChannels {}
false

Object.is实际上是在说channels的更新状态不同于先前的状态。但是,TSChart组件不会重新呈现,而是与先前选择的时间序列保持一致。

关于我所缺少的任何线索吗?

0 个答案:

没有答案