How React rerenders tree, if both parent and child components are dependent from one Redux store prop?

自古美人都是妖i 提交于 2019-12-23 05:49:08

问题


I have Layout component, which checks if user is logged in. It simply examines user prop in Redux store. If it is, it renders children, otherwise Login.

  • Layout.jsx
const Layout = ({ user, children }) => {
  if (user) return children;
  return <Login />;
};

export default connect(state => ({ user: state.user }))(Layout);
  • Profile.jsx
const Profile = ({ user }) => <div>{user.name}</div>;

export default connect(state => ({ user: state.user }))(Profile);
  • App itself
<Layout>
  <Profile />
</Layout>

The issue is when Profile component is rendered and I log out, I get can not read property name of undefined.

I expect Profile component not to be rendered at all, because it is how Layout works. But looks like React first tries updating Profile component and fails.

For now I ended up returning null from Profile if there is no user, but it's not ideal.

So if both parent and child components are dependent from one Redux store prop, React rerenders them from down to top, from top to down, or simultaneously? Is there canonical or best practice way to avoid it?

来源:https://stackoverflow.com/questions/47631930/how-react-rerenders-tree-if-both-parent-and-child-components-are-dependent-from

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!