Redux:Child 在 parent 之前接收道具

Redux: Child receiving props before parent

我的应用程序的状态可能有也可能没有 user object。

我有两个容器和两个组件:

父容器:

const mapStateToProps = (state) => ({
  showUserDetails: Boolean(state.user),
})

export default connect(mapStateToProps)(ParentComponent)

父组件:

const ParentComponent = ({ showUserDetails }) => (
  <div>
    {showUserDetails && <ChildContainer />}
  </div>
)

子容器:

const mapStateToProps = (state) => ({
  name: state.user.name,
})

export default connect(mapStateToProps)(ChildComponent)

子组件:

const ChildComponent = ({ name }) => (
  <h1>{name}></h1>
)

但是我 运行 遇到这样的场景,在设置 state.user = null 的操作之后,ChildContainer 尝试在 ParentContainer 之前呈现,因此尽可能抛出异常' 访问 null.name

这是 Redux 的预期行为,child 容器可以在 parent 之前 re-render 吗?在经典的 React 流程中,不会发生此错误。

我很欣赏在这个人为的例子中,可以在 ParentComponent 中调用 <ChildComponent name={user.name} /> 而不是使用容器。但在现实世界中,我有深层嵌套的组件访问状态的许多不同部分,所以不能简单地传递道具。

无论 child 组件是否包含在 parent 中,更新都会发生。由于更新时它在 DOM 中,因此 connect 将尝试更新您的组件。

最简单的解决方法是在提取用户名 (state.user.name,) 时插入安全检查并将其替换为 (state.user && state.user.name,).

或者,当然 - 替代方案。从 parent.

传下来

为了进一步解释,从 parent 向下发送的 props 将首先在 parent 中进行评估,然后更新将在层次树中向下传播。但是,由于 name 的支持实际上直接来自状态树,因此您需要对其进行一些安全检查。

即使 parent 在其自身的后续更新之后将决定不应再呈现 child(因为 showUserDetails 现在将评估为 false)。

你在批处理你的 Redux dispatches 吗?如果不仔细阅读 v3.0.0 发行说明:

https://github.com/reactjs/react-redux/releases/tag/v3.0.0

它建议使用 redux-batched-updates 模块,但或多或​​少不推荐使用 redux-batched-subscribe

这样使用:

import { unstable_batchedUpdates as batchedUpdates } from 'react-dom';
import { batchedSubscribe } from 'redux-batched-subscribe';

const store = createStore(reducer, intialState, batchedSubscribe(batchedUpdates));