--- tags: hermes --- # React useful code ### 用於觀察哪個東西update導致re-render ``` javascript componentDidUpdate(prevProps, prevState) { Object.entries(this.props).forEach(([key, val]) => prevProps[key] !== val && console.log(`Prop '${key}' changed`) ); if (this.state) { Object.entries(this.state).forEach(([key, val]) => prevState[key] !== val && console.log(`State '${key}' changed`) ); } } ``` ### setState順序 ``` javascript this.setState({ key: 'xxx' }, () => { // do something }) ``` ### 延遲範例 1. setTimeout ``` javascript this.setState({ loading: true }) setTimeout(() => { this.setState({ loading: false }) }, 3000) ``` 2. await ``` javascript function sleep(delay = 0) { return new Promise((resolve) => { setTimeout(resolve, delay); }); } async test() { // call in async function await sleep(1000); } ``` ### get視窗大小 ``` window.innerWidth ``` ### copy log ![](https://i.imgur.com/0QeEose.png) ~~~ JSON.stringify(temp1) ~~~ ### call child component's function - ref: https://stackoverflow.com/questions/37949981/call-child-method-from-parent ~~~javascript const { Component } = React; class Parent extends Component { constructor(props) { super(props); this.child = React.createRef(); } onClick = () => { this.child.current.getAlert(); }; render() { return ( <div> <Child ref={this.child} /> <button onClick={this.onClick}>Click</button> </div> ); } } class Child extends Component { getAlert() { alert('getAlert from Child'); } render() { return <h1>Hello</h1>; } } ReactDOM.render(<Parent />, document.getElementById('root')); ~~~ ### React.Fragment 特性 ```<React.Fragment>```可以延續```<Typography display="inline">```的inline效果 不會斷行 ### Grid 應用 ~~~ <Grid container spacing={2} justifyContent="center" alignItems="center"> </Grid> ~~~ - justifyContent 是左右置中 - alignItems 是上下置中