我有一个Class React组件,如果浏览器pathName为/ exp,则使用功能性的Hook组件
页面加载后,我的应用程序组件的状态更改为大约3-4次,
如果道具未更改,如何防止Example挂钩重新安装?
import React, { useState } from 'react';
function Example() {
console.log("i mounted")
}
__
export default class App extends Component {
state={key:"value"} <--------------------------------------MAIN APP STATE CHANGES 3 times
componentDidMount(){
//I change App state 3 times with conditional code
}
render() {
return (
<Router>
<Switch>
<Route path="/exp">
<Example prop="I have not changed" /> <-----------------PREVENT MULTIPLE MOUNTINGS
</Route>
</Switch>
</Router>
)
}
答案 0 :(得分:1)
const Chat = React.memo(props => {
console.log("Greeting Comp render");
return <></>
});
export default Chat
//This worked for me
您可以使用React.memo并在更改道具时进行渲染
function MyComponent(props) {
/* render using props */
}
function areEqual(prevProps, nextProps) {
/*
return true if passing nextProps to render would return
the same result as passing prevProps to render,
otherwise return false
*/
}
export default React.memo(MyComponent, areEqual);
或
shouldcomponentupdate(如果是类组件)
shouldComponentUpdate(nextProps, nextState)
注意:此方法仅作为性能优化存在。不要依靠它来“阻止”渲染,因为这可能会导致错误。