首页 > 解决方案 > 反应钩子出错:组件的值不断重新渲染

问题描述

又是我,我仍然无法使用 redux 的 react-hook

我正在尝试使用 useMemo 方法从 firestore 获取数据集合。

UserDetailed 组件将在用户登录并单击 SignedIn 组件中名为“Profile”的下拉菜单项后调用。

在 App.jsx 中,我声明了使用 UserDetailed 组件的路径:

const App = () => {
return (
    <Fragment>
        <ModalManager />  
        <Switch>
            <Route exact path='/' component={HomePage}/>
        </Switch>
        <Route path='/(.+)' render={() => (
            <Fragment>
                // NavBar component is placed here
                <NavBar />
                <Container className="main">
                    <Switch>
                  <Route exact path='/blogs' component={BlogDashboard} />
                  <Route path='/blogs/:id' component={BlogDetailedPage} />
                  // Route for UserDetailed component is placed here
                  <Route path='/profile/:id' component={UserDetailed}/>      
                    </Switch>
                </Container>
            </Fragment>)} 
        />
    </Fragment>
);
};
export default App;

SignedIn 放置在导航栏中:

在 NavBar.jsx 中:

const NavBar = ({history}) => {
const firebase = useFirebase();
const auth = useSelector(state => state.firebase.auth, []);

const handleLogout = () => {
    firebase.auth().signOut().then(() => {
        history.push('/');
    });
};

const authenticated = auth.isLoaded && !auth.isEmpty;

return (
    <Menu fixed='top'>
        <Container>
            <Menu.Item as={NavLink} exact to='/blogs' name="Blogs"/>
            {authenticated ? 
                (<SignedIn signOut={handleLogout} />) : 
                (<SignedOut />)
            }
             </Container>
         </Menu>
)
}    

在 SignedIn.jsx 中:

const SignedIn = ({signOut}) => {
const auth = useSelector(state => state.firebase.auth, []);

return (
 <Menu.Item position='right'>
  <Image avatar spaced='right' src={profile.photoURL} />
  <Dropdown text="My profile">
    <Dropdown.Menu>
       // this is where the SignedIn component is called:
      <Dropdown.Item as={Link} to={`/profile/${auth.uid}`} text='Profile'/> 
      <Dropdown.Item onClick={signOut} text='Sign Out'/>
    </Dropdown.Menu>
  </Dropdown>
 </Menu.Item>
);
};

在 UserDetailed.jsx 中:

const UserDetailed = ({match: {params}}) => {
    const firebase = useFirebase();
    const isCurrentUser = firebase.auth().currentUser.uid === params.id;
    console.log(isCurrentUser);  

    const getUserProfile= useMemo(() => ({
       collection: 'users',
       doc: params.id,
       storeAs: 'userProfile'
    }), [params.id]);

    console.log(getUserProfile);

useFirestoreConnect(getUserProfile); //get datas from here

return (
    <div></div>
);
};
export default UserDetailed;  

“isCurrentUser”和“getUserProfile”确实返回了我预期的值,但它只是继续重新渲染,直到达到最大深度并抛出“超出最大更新深度”错误。为什么会这样?

标签: reactjsgoogle-cloud-firestorereact-hooks

解决方案


推荐阅读