React函数式组件与Class组件对比

333 阅读1分钟

函数式组件与Class组件对比

// 两者状态、生命周期函数、路由跳转、获取动态参数方式对比
import React, { useState, useEffect } from 'react';
import { Link, useParams, useHistory } from 'react-router-dom'
import { Button } from 'antd'
import 'antd/dist/antd.css'
//  import之前不能有变量声明,否则会报错

// 函数式组件
export default function App() {
    const [count, setCount] = useState(10)                  //1.状态
    // const [a, b] = [1,2]   解构赋值
    useEffect(() => {					    //2.类似周期函数
        console.log('执行了useEffect.')				
        //Ajax请求...
    }, [])
    // 组件加载时/组件更新时 调用 useEffect  
    // useEffect基于 componentDidMount 与 componentDidUpdate
    // useEffect(fn,[])第二个参数为空数组,就只执行一次
    const params = useParams()				   //3.获取动态路由参数
    const history = useHistory()			   //4.路由跳转
    return <div>
        <p>
            当前count次数:{count}
        </p>
        <Button onClick={() => { setCount(count + 1) }}>更新次数</Button>
		当前参数:{params.id}			  //3.获取动态路由参数
        <br/>
        <Button onClick={() => {
            history.push('/')				  //4.路由跳转
        }}>跳转首页</Button>
    </div>
}

//Class组件
//有状态的
class App extends React.Component {
    state = {
        count: 10						//1.状态
    }
	// 用箭头函数,保留this
    handleUpdate=()=>{
        this.setState({ count: this.state.count+1 });
    }
    handleJump = () => {
        this.props.history.push('/login')			//4.路由跳转
    }
	
    componentDidMount(){...}					//2.周期函数
    
    render() {
        return <div>						
            <p>当前参数值为:{this.props.match.params.id}</p>    //3.获取动态路由参数	
            <Link to="/login">登录页面</Link>
            <br />{count}
            <Link to="/home">主页面</Link>
            <br />
            <Button type="primary" onClick={this.handleJump}>登录跳转</Button>
        </div>
    }
}

export default App;

JSX语法规则

  1. 基本语法规则 a. 遇到 <开头的代码, 以标签的语法解析: html 同名标签转换为 html 同名元素, 其它标签需要特别解析 b. 遇到以 { 开头的代码,以 JS 语法解析: 标签中的 js 代码必须用{}包含
  2. babel.js 的作用 a. 浏览器不能直接解析 JSX 代码, 需要 babel 转译为纯 JS 的代码才能运行 b. 只要用了 JSX,都要加上 type="text/babel", 声明需要 babel 来处理