首页 > 解决方案 > useSelector 不会像 Redux 中的 connect 那样重新渲染组件

问题描述

我试图搜索这个问题,但大部分主题都是关于 mutate 但在我的情况下它是一个原始数据类型,这里是示例代码:

// ParentPage.jsx
import { useSelector } from 'react-redux';

const selectShowFooterFlag = (state) => {
    return state.shouldShowFooter;
}

const ParentPage = () => {
    const shouldShowFooter = useSelector(selectShowFooterFlag);
    const ChildComponent = useSelector(selectChildComponent);

    return (
        <p>{String(shoudShowFooter)}</p>
        <ChildComponent shoudShowFooter={shoudShowFooter}>
    )
}
export default ParentPage;
// ChildPage

const ChildPage = ({ shoudShowFooter }) => {

    useEffect(() => {
        dispatch(shouldShowFooterState(false));
        return () => {
             dispatch(shouldShowFooterState(true));
        }
    });

    return (
        <p>String(shoudShowFooter)</p>
    )
}
// reducer
const initalState = {
    isPageFooterRequired: true,
};

export const pagesReducer: (draft, action) = produce((draft = initialState, action: DispatchAction) => {
    switch() {
        case SHOW_FOOTER:
            draft.shoudShowFooter = action.payload;
            break;

        default:
           return draft;
    }
});

在此示例中,当子组件挂载时,它将shoudShowFooterfalse预期设置。在ChildComponentredux 存储中更新时,当前 ChildComponent 将卸载并将其设置shoudShowFootertrue. 我已经检查过了,它是正确的(selectShowFooterFlag已被调用)。

但问题是shoudShowFooterredux 发生了变化,但ParentPage没有使用新状态重新渲染,因此新的 ChildComponent 无法接收 reducer 存储中的最新数据(我已经检查了 Redux devtools 的最新状态数据)。

更有趣的一点是,当我切换到使用 connect 时,一切正常。

import { connect } from 'react-redux';

const selectShowFooterFlag = (state) => {
    return state.shouldShowFooter;
}

const ParentPage = () => {
    const ChildComponent = useSelector(selectChildComponent);

    return (
        <p>{String(shoudShowFooter)}</p>
        <ChildComponent shoudShowFooter={shoudShowFooter}>
    )
}

const mapStateToProps = (state) => {
    return {
         shouldShowFooter: selectShowFooterFlag(state);
    }
}
export default connect(mapStateToProps)(ParentPage);

我认为 useSelector 会给我们与连接相同的行为,当状态数据发生变化时会重新渲染组件。但似乎不是在这种情况下。

如何useSelector使用最新数据重新渲染触发器connect?或者我如何调试这个案例来看看为什么 React 不重新渲染应用程序?

标签: javascriptreactjsreduxreact-redux

解决方案


推荐阅读