当在 redux 中调度 store 变量时,React 组件不会重新渲染

问题描述

import React,{ useEffect,useState } from 'react';
import { usedispatch,useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';

import { logedInAction } from '../../redux/userDetails/userDetailsActions';

import Loading from '../Loading/Loading';
import ChatList from './ChatList/ChatList';

const MainWindow = () => {
    const { isLoged } = useSelector( state => state.userDetails );
    const dispatch = usedispatch();
    const history = useHistory();

    const [ loading,setLoading ] = useState(true);

    useEffect( () => { 
        const dataFetcher = async () => {
            try {
                const res = await fetch( "http://localhost:4000/",{ credentials: 'include' });
                // doing some code and dispatching isLoged variable to true
                setLoading(false);
            } catch(e) { console.log(e); }
        }
        dataFetcher();
    },[ dispatch,history ] );

    return(
        <>
            {
                loading ? <Loading  /> : 
                isLoged ? <ChatList /> : <div> error</div>
            }
        </>
    );
}

export default MainWindow;

当这个程序启动时,变量 lodaing 为真;所以组件被渲染。 运行 datafecter 后,变量 lodaing 变为 false,isLoged 变为 true。

最初 isLoged 是假的;我从 redux 商店获得了它。当我在两者之间将其调度为 true 时,它​​会将其值更改为 true (我看到 react dev 工具中的值更改)。但它并没有重新渲染它的价值。

即,如果 lodaing 为假且 isLoged 为真,我应该获取组件。但不幸的是,我收到了错误组件。这意味着 isLoged 的​​ 值未呈现。

如何解决这个 Redux 渲染问题?

解决方法

这个问题可能是由于 React 完全更新本地状态所需要的延迟造成的,因此您需要使用 useEffect 仅在状态 loading 发生变化时分派您的操作。所以:

import React,{ useEffect,useState } from 'react';
import { useDispatch,useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';

import { logedInAction } from '../../redux/userDetails/userDetailsActions';

import Loading from '../Loading/Loading';
import ChatList from './ChatList/ChatList';

const MainWindow = () => {
    const { isLoged } = useSelector( state => state.userDetails );
    const dispatch = useDispatch();
    const history = useHistory();

    const [ loading,setLoading ] = useState(true);

    useEffect( () => { 
        const dataFetcher = async () => {
            try {
                const res = await fetch( "http://localhost:4000/",{ credentials: 'include' });
                setLoading(false);
            } catch(e) { console.log(e); }
        }
        dataFetcher();
    },[ dispatch,history ] );

    useEffect( () => { 
       // this "if" guarantee that the local state `loading` and the store state `isLoged` will be false at this point
       if(!loading && !isLoged) {
         // doing some code and dispatching isLoged variable to true
       }
       
    },[ loading ] );

    return(
        <>
            {
                loading ? <Loading  /> : 
                isLoged ? <ChatList /> : <div> error</div>
            }
        </>
    );
}

export default MainWindow;