我有 Layout 组件,它会检查用户是否已登录 . 它只是检查Redux商店中的 user prop . 如果是,它会渲染孩子,否则 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本身
<Layout>
  <Profile />
</Layout>

问题是当 Profile 组件被渲染并且我退出时,我得到 can not read property name of undefined .

我希望 Profile 组件根本不会被渲染,因为它是 Layout 的工作方式 . 但看起来React首先尝试更新 Profile 组件并失败 .

现在,如果没有用户,我最终会从 Profile 返回 null ,但这并不理想 .

因此,如果父组件和子组件都依赖于一个Redux商店道具,React会从下到上,从上到下或同时将它们重新呈现?是否有规范或最佳实践方法来避免它?