1. 程式人生 > 其它 >Spring Boot2.x自定義錯誤頁面

Spring Boot2.x自定義錯誤頁面

父元件App.tsx:

import React, {useState} from 'react';
import Clock from './Clock'
import './app.css';

function App() {
  const [clockDom, setClockDom] = useState<JSX.Element>(<div/>);

  const changeClock = (state: Boolean, name: String)=> {
    if (state) {
      setClockDom(<Clock name={name}/>);
    } else
{ setClockDom(<div/>); } } return ( <div className="app"> <div>app元件</div> <button onClick={()=> {changeClock(true, "北京時間")}}>渲染</button> <button onClick={()=> {changeClock(false, "")}}>刪除</button> <button onClick={()=> {changeClock(true
, "北京時間")}}>北京時間</button> <button onClick={()=> {changeClock(true, "美國時間")}}>美國時間</button> {clockDom} </div> ); } export default App;

子元件Clock.jsx:

import React from 'react'
import './clock.css';
export default class Clock extends React.Component {
    constructor(props) { 
// 資料的初始化,接收2個引數,props、context配合super()使用否則this指向錯誤 super(props); const { name } = this.props; this.state = { timerID: null, name, date: new Date().toLocaleTimeString() }; } componentWillMount() { // 服務端渲染時呼叫,在整個生命週期中只會呼叫一次 console.log("服務端渲染"); } // 初始化:元件第一次渲染完成,dom節點已生成。可以在這裡請求ajax返回資料setState後,元件會重新渲染。 componentDidMount() { // 在整個生命週期中只會呼叫一次 console.log("初始化"); this.setState({timerID: setInterval(() => this.tick(), 90000)}); } componentWillUnmount() { // 元件銷燬後呼叫,多用於清理記憶體空間 clearInterval(this.state.timerID); } componentWillReceiveProps(newProps) { // 當從父類接收到新的 props 前呼叫。 // newProps就是父級最新傳入的資料 // 對比this.props 和 nextProps 將nextProps的state改為當前的state,頁面可以重新渲染。 console.log("從父級接收新資料props", this.props, newProps); this.setState({name: newProps.name}); } shouldComponentUpdate() { // 元件接受到新屬性、新狀態呼叫 // 返回true則元件正常執行 // 返回false則阻止render呼叫,後面的函式不會被繼續執行了, console.log("元件接受到新屬性、新狀態呼叫"); return true // 必須返回 true 或者 false } componentWillUpdate(newProps, nextState, newContext) { // 元件更新前呼叫 // shouldComponentUpdate,返回true後,元件進入重新渲染的程序。 // 此時進入componentWillUpdate中,也可以同樣拿到nextProps和nextState console.log("元件更新前", newProps, nextState, newContext); } componentDidUpdate(prevProps, prevState, Snapshot) { // 元件更新後呼叫 // 在這裡可以拿到prevProps和prevState,也就是更新前的props和state console.log("元件更新後", prevProps, prevState, Snapshot); } tick() { this.setState({date: new Date().toLocaleTimeString()}); } render() { // 渲染元件 return ( <div className="clock"> <div>Clock元件</div> <button onClick={()=> {this.tick()}}>更新時間</button> <div>{this.state.name}:{this.state.date}</div> </div> ); } }