gpt4 book ai didi

reactjs - 如何防止 React Native 多次重新渲染

转载 作者:行者123 更新时间:2023-12-04 14:46:46 24 4
gpt4 key购买 nike

目前我的组件渲染了 4 次。看起来它正在为每个 Prop 渲染。如果我删除除网络之外的 Prop ,那么它只会渲染 1 次,但我确实需要其他 Prop 。我在 componentDidUpdate 中使用了 if 语句,因为我需要检测变化,但是我渲染了 4 次并且我的网络 Prop 是相同的

export class Camera extends Component {
componentDidUpdate(prevProps, prevState){
if (prevProps.network !== this.props.network){
this.connect(this.props.network)
console.log('rendering')
}
}

connect=()=>{
//
}

render() {
return (
<View>
<Text>
Hello World
</Text>
</View>
)
}
}

export default function (props) {
return (
<Camera
navigation={props.navigation}
route={props.route}
network={React.useContext(NetworkContext)}
/>
);
}

最佳答案

因为你使用的是 React 类组件而不是钩子(Hook),也许你可以使用shouldComponentUpdate 生命周期方法。

shouldComponentUpdate(nextProps, nextState)

https://reactjs.org/docs/react-component.html#shouldcomponentupdate

基本上,如果您希望您的组件不在某些 Prop /状态更改时呈现,您可以返回 false

例如,以下内容应该只在网络属性更改后才重新渲染组件,而不是任何其他属性更改

shouldComponentUpdate(nextProps, nextState){
if (nextProps.network !== this.props.network){
return true
} else {
return false
}
}

关于reactjs - 如何防止 React Native 多次重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69888334/

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