react-更新孩子但不是直接父母

IT技术 reactjs
2021-04-30 11:13:54

我有一个 React 组件层次结构,看起来有点像这样:

var A = React.createClass({
    render: function() {
        /* stuff */
    }
});    
var B = React.createClass({
    render: function() {
        return dom.div(null, this.props.children);
    }
});    
var C = React.createClass({
    render: function() {
        return dom.div(null, B(null, A()));
    }
});

本质上,C 将 A 元素作为子元素传递给 B,然后 B 渲染它。

现在我想更新 A 元素而不是 B我不清楚在这种情况下 shouldComponentUpdate 的语义是什么。如果我在 B 中实现了 shouldComponentUpdate,我是否需要考虑我的孩子是否应该更新?不更新孩子的直接父母就不可能更新孩子吗?

1个回答

如果你想更新 A 而不是 B,你应该在它自己的组件中实际描述 A 的行为 - 例如,在 A 的钩子中订阅一些第三方的真实来源(根据Flux架构存储componentDidMount

这是唯一的方法——如果 A 无法控制它自己的流程,它只会在 B(父级)render()调用时更新——你已经可以通过 B's (and \ or it's parents') 来控制它shouldComponentUpdate