Javascript can';t使用useEffect对未安装的组件问题执行react状态更新
我正在尝试将我的用户重定向到专用路由。我使用redux thunk从数据库中获取用户信息,使用storeUser(),如果信息存在,则用户继续,否则会重定向回主页。然而,它并没有像预期的那样工作。它会在应该继续的时候重定向回主页。我可以使用基于类的语法和componentDidMount来实现这一点。我试图通过使用authChecked状态来确定组件何时完成渲染来解决无法访问componentDidMount的问题Javascript can';t使用useEffect对未安装的组件问题执行react状态更新,javascript,reactjs,redux-thunk,Javascript,Reactjs,Redux Thunk,我正在尝试将我的用户重定向到专用路由。我使用redux thunk从数据库中获取用户信息,使用storeUser(),如果信息存在,则用户继续,否则会重定向回主页。然而,它并没有像预期的那样工作。它会在应该继续的时候重定向回主页。我可以使用基于类的语法和componentDidMount来实现这一点。我试图通过使用authChecked状态来确定组件何时完成渲染来解决无法访问componentDidMount的问题 const PrivateRoute = (props) => {
const PrivateRoute = (props) => {
const [authChecked, handleAuthChecked] = useState(false);
const [isAuth, handleIsAuth] = useState(false);
useEffect(() => {
props
.storeUser()
.then(() => {
props.user.email ? handleIsAuth(true) : handleIsAuth(false);
handleAuthChecked(true);
})
.catch(() => {
handleAuthChecked(true);
});
}, [props]);
if (authChecked) {
return isAuth ? <props.component /> : <Redirect to="/" />;
}
return null;
};
const mapStateToProps = (state) => {
return {
user: state.user,
};
};
export default connect(mapStateToProps, { storeUser })(PrivateRoute);
const privaterote=(道具)=>{
const[authChecked,handleAuthChecked]=使用状态(false);
const[isAuth,handleIsAuth]=useState(false);
useffect(()=>{
道具
.storeUser()
.然后(()=>{
props.user.email?handleIsAuth(true):handleIsAuth(false);
handleAuthChecked(正确);
})
.catch(()=>{
handleAuthChecked(正确);
});
}[道具];
如果(已选中){
返回isAuth?:;
}
返回null;
};
常量mapStateToProps=(状态)=>{
返回{
用户:state.user,
};
};
导出默认连接(MapStateTops,{storeUser})(PrivateRoute);
但代码将始终重定向用户。即使props.user.email为true,isAuth也不会返回true。它在有机会运行handleIsAuth(true)之前运行并重定向。您有两个问题可能导致您看到的缺陷:
useffect
中的函数范围和对storeUser
的回调引起的。不要依赖回调来确定用户是否有电子邮件地址,只需在渲染条件下执行此操作,并让redux+react render cycle帮助您解决问题storeUser
操作。不是每次props
更新时const PrivateRoute = (props) => {
const [authChecked, handleAuthChecked] = useState(false);
useEffect(() => {
props
.storeUser()
.then(() => {
handleAuthChecked(true);
})
.catch(() => {
handleAuthChecked(true);
});
}, []);
if (authChecked) {
return !!props.user.email
? <props.component />
: <Redirect to="/" />;
}
return null;
};
const mapStateToProps = (state) => {
return {
user: state.user,
};
};
const privaterote=(道具)=>{
const[authChecked,handleAuthChecked]=使用状态(false);
useffect(()=>{
道具
.storeUser()
.然后(()=>{
handleAuthChecked(正确);
})
.catch(()=>{
handleAuthChecked(正确);
});
}, []);
如果(已选中){
return!!props.user.email
?
: ;
}
返回null;
};
常量mapStateToProps=(状态)=>{
返回{
用户:state.user,
};
};
每次组件呈现时,都会进行StoreUser()异步函数调用。您必须确保它只被调用一次,方法是在useffect的第二个参数中提供[]。