【发布时间】:2017-01-29 03:36:35
【问题描述】:
想象一下下面的 React 结构:
SmartComponentA -> DumbComponentB -> SmartComponentC
还可以想象 SmartComponentA 和 SmartComponentC 在其mapStateToProps 函数中分别连接到不同的状态切片。
最后,假设我们将console.log 放在每个组件的渲染方法中。
当我实际尝试这个时,在第一次渲染时,我看到所有组件都按预期记录。但是,如果我更改 SmartComponentC 的数据,我只会看到一条日志消息(C 的日志消息),并且看不到 SmartComponentA 或 DumbComponentB 记录任何内容。这怎么可能? react-redux 如何让 React 在不更新父母的情况下更新孩子?
我会假设 shouldComponentUpdate 内部的 shouldComponentUpdate 的 the overriding connect 将意味着 SmartComponentA 不会被重新渲染(因为它的状态部分没有改变),因此会导致短路- 防止 SmartComponentC 重新渲染的电路。虽然 connect 的实现与纯渲染混合不同,两者都通过更改 shouldComponentUpdate 来工作,但纯渲染文档明确指出,如果父级不这样做,React 将“纾困”(正如他们所说) t需要重新渲染:
对于 C2 的子树和 C7,它甚至不必计算虚拟 DOM,因为我们在
shouldComponentUpdate上进行了救助。
如果我的问题仍然不明确,这里是设置的伪代码,我在问为什么我可以继续输入 C 的输入,它只将 C 的消息记录到控制台而不是A和B(为什么不短路)?
//////////////////////////////////////////////
const SmartComponentA = (props) => {
console.log('rendering SmartComponentA');
return <DumbComponentB bData={props.bData} />;
};
const mapStateToProps = (state) => { bData: state.bData };
export default connect(mapStateToProps)(SmartComponentA);
//////////////////////////////////////////////
const DumbComponentB = (props) => {
console.log('rendering DumbComponentB');
return (
<div>
{props.bData}
<SmartComponentC />
</div>
);
}
export default DumbComponentB;
//////////////////////////////////////////////
const SmartComponentC = (props) => {
console.log('rendering SmartComponentC');
return (
<div>
<input value={props.cValue} onChange={props.changeCValue} />
</div>
);
}
const mapStateToProps = (state) => { cValue: state.cValue };
export default connect(mapStateToProps, { changeCValue })(SmartComponentC);
//////////////////////////////////////////////
在第一次渲染时,我会看到所有日志消息,然后如果我继续输入,每次按键时我只会看到 C 的日志消息。
【问题讨论】:
标签: react-redux