简体   繁体   English

将 Redux 与 useEffect Hook 混合

[英]Mixing Redux with useEffect Hook

I read that this is theoretically OK.我读到这在理论上是可以的。 In my small use case, I'm running into an issue, where mixing those technologies leads to double re-rendering.在我的小用例中,我遇到了一个问题,混合这些技术会导致双重重新渲染。

First, when redux dispatch is executed and some components use a prop via useSelector.首先,当 redux dispatch 被执行并且一些组件通过 useSelector 使用一个 prop 时。 Then, after the functional component is already re-rendered, a useEffect hook is being applied which updates the state of some property.然后,在功能组件已经重新渲染后,将应用一个 useEffect 挂钩来更新某些属性的 state。 This update re-triggers the render again.此更新再次重新触发渲染。

Eg the below console log prints out twice in my case.例如,在我的情况下,下面的控制台日志会打印两次。

Question: should I remove the useEffect and useState and integrate it into redux' store?问题:我应该删除 useEffect 和 useState 并将其集成到 redux 的 store 中吗?

import {useSelector} from "react-redux";
import React from "react";


const Dashboard = (props) => {
    const selFilters = useSelector((state) => state.filter.selectedDashboardFilters);
    const [columns, setColumns] = React.useState([]);

    React.useEffect(() => {
            let newColumns = getColumns();
            setColumns(newColumns)
        }, [selFilters]
    )
    
    console.log("RENDER")
    
    return (
        <h1>{columns.length}</h1>
    )
}

If columns needs to be recomputed whenever selFilters changes, you almost certainly shouldn't be recomputing it within your component.如果每当selFilters更改时需要重新计算columns ,则几乎可以肯定不应该在组件中重新计算它。 If columns is computed from selFilters , then you likely don't need to store it as state at all.如果columns是从selFilters计算的,那么您可能根本不需要将其存储为 state。 Instead, you could use reselect to create a getColumns() selector that derives the columns from the state whenever the relevant state changes.相反,您可以使用reselect创建一个getColumns()选择器,只要相关的 state 发生更改,该选择器就会从 state 派生列。 For example:例如:

const getColumns = createSelector(
  state => state.filter.selectedDashboardFilters,
  selFilters => {
    // Compute `columns` here
    // ...
    return columns
  }
)

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

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