gpt4 book ai didi

reactjs - 如何区分React组件渲染的原因 : something from the inside or from the outside of the component?

转载 作者:行者123 更新时间:2023-12-03 13:38:29 25 4
gpt4 key购买 nike

我有两个嵌套的 react 组件:OuterInner。每当我调用 InnersetState 时,就会调用内部组件的 render 。另外,每当我调用外部组件的 setState 时,外部组件和内部组件的 render 函数都会被调用。我想区分这两种情况并检测是什么导致了内部组件的渲染。我的 Innerrender 函数的行为应该有所不同,具体取决于此。我怎样才能做到这一点?

最佳答案

您可以利用这样一个事实:仅当组件接收新 Prop 时才调用 componentWillReceiveProps(请在此处查看: http://busypeoples.github.io/post/react-component-lifecycle/ ),而不是在调用 setState 时调用,重要的是它们甚至不必不同比现有的 Prop (根据 https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops )。所以你应该能够做一些类似的事情

componentWillReceiveProps() {
this.setState({parentUpdated: true});
}

render() {
if (this.state.parentUpdated) {
// Render one way
} else {
// Render the other way
}
}

尽管您还需要在渲染后以某种方式取消设置,或者只是确保对 this.setState 的每次调用也包含 {parentUpdated: false}。

关于reactjs - 如何区分React组件渲染的原因 : something from the inside or from the outside of the component?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38514916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com