Example:
props is not updated permanently while shouldComponentUpdate returns false
import { render, Component } from "preact";
class A extends Component {
state = { a: 0 };
componentDidMount() {
this.setState({ a: 1 }); // update props
}
render() {
return <B a={this.state.a} />;
}
}
class B extends Component {
state = { now: "---" };
timer = 0;
updateState = () => {
this.setState({ now: new Date().toString() });
};
componentDidMount() {
this.timer = setInterval(this.updateState, 1000);
}
componentWillUnmount() {
clearInterval(this.timer);
}
shouldComponentUpdate(nextProps, nextState) {
if (nextProps !== this.props) {
console.log(
"called infinitely!! it must be called only once.",
new Date(),
nextProps.a,
this.props.a
);
// nothing do when props changed
return false;
}
return true;
}
render() {
return (
<p>
{this.state.now}, {this.props.a}
</p>
);
}
}
render(<A />, document.getElementById("root"));
https://codesandbox.io/s/o57vp43o3q
Looks like the props reference just needs to be updated in the sCU:false codepath.
note: This behavior is sometimes used to compute props.
// this causes an infinite loop
shouldComponentUpdate(nextProps, nextState) {
if (nextProps !== this.props) {
this.setState(recomputeProps(nextProps));
return false;
}
return true;
}
this one? fmm... I don't know much about vnode. is this all?
https://github.com/developit/preact/blob/753d8849997612f2fa3d168a28ff4dfba65b39bc/src/diff/index.js#L120-L121
Most helpful comment
Looks like the props reference just needs to be updated in the sCU:false codepath.