如何解决当在 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 的 值未呈现。
解决方法
这个问题可能是由于 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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。