我在函数组件中使用带有依赖项的useEffect钩子,这样依赖项就会发生变化,useEffect函数将像这样重新运行:
const [show, setShow] = React.useState(false);
React.useEffect(() => {
console.log("Do something")
} , [show]);我想知道react的类组件中有什么可用于这样做的?是否有任何生命周期方法具有此功能?
发布于 2021-09-19 11:39:50
您可以使用componentDidMount和componentDidUpdate的组合
componentDidMount(){ //use this method if you want to trigger the side effect first time
console.log("Do something")
}
componentDidUpdate(prevProps,prevState) {
if (this.state.show !== prevState.show) {
console.log("Do something");
}
}发布于 2021-09-19 11:52:15
若要控制组件,请使用shouldComponentUpdate (文章链接)。它有两个参数:nextProps和nextState。您可以比较this.state.field和nextState.field,如果它们不同,则产生副作用:
class ClickButton extends React.Component {
constructor(props) {
super(props);
this.state = {class: "off", label: "press"};
this.press = this.press.bind(this);
}
shouldComponentUpdate(nextProps, nextState){
if(nextState.class !== this.state.class){
return true
}
return false;
}
press(){
var className = (this.state.class==="off")?"on":"off";
this.setState({class: className});
}
render() {
return <button onClick={this.press} className={this.state.class}>{this.state.label}</button>;
}
}
如果ypu从该方法返回true,则说明组件应该更新,false以其他方式表示,组件不会更新。
您还可以从PureComponent (PureComponent)扩展,它将自动跟随道具和状态:
class ClickButton extends React.PureComponent {
constructor(props) {
super(props);
this.state = {class: "off", label: "press"};
this.press = this.press.bind(this);
}
press(){
var className = (this.state.class==="off")?"on":"off";
this.setState({class: className});
}
render() {
return <button onClick={this.press} className={this.state.class}>{this.state.label}</button>;
}
}
但它作了一个肤浅的比较(通过参考)。如果您的状态中有嵌套字段,并且它们正在更改,则PureComponent不会重新添加组件。
还有其他方法,如componentDidUpdate (链接)和componentDidMount (链接)。首先,当组件重登时调用:
componentDidUpdate(prevState) {
if (this.state.userID !== prevState.userID) {
this.fetchData(this.state.userID);
}
}
谈到第二个问题,它将在DOM中设置组件时调用。
在您的例子中使用componentDidUpdate
https://stackoverflow.com/questions/69242802
复制相似问题