有狀態組件 和 無狀態組件的區別


一 、有狀態組件 (stateful components)

         平時用的大部分是 有狀態組件

        寫法:

        

import React,{Component} from 'react';

export default class Bottom extends Component{
constructor(props){
super(props);
this.sayHi = this.sayHi.bind(this)//記得綁定this,否則this指向可能會出錯
}

sayHi(){
let {name} = this.props
console.log(`Hi ${name}`);
}
render(){
let {name} = this.props
let{sayHi} =this;
return(
<div>
<h1>{`Hello, ${name}`}</h1>
<button onClick ={sayHi}>Say Hi</button>
</div>
)
}

}

二、無狀態組件 (stateless components)

       它是一種函數式組件,沒有state, 接收Props,渲染DOM,而不關注其他邏輯

       寫法:

        

import React,{Component} from 'react';
export default function Bottom(props){
let{name} = props
const sayHi = () => {
console.log(`Hi ${name}`);
}
return (
<div>
<h1>Hello, {name}</h1>
<button onClick ={sayHi}>Say Hi</button>
</div>
)
}


兩都在性能方面比較,無狀態組件性能更高些。

調用無狀態組件方式, 方式 2 性能高:
1、<Bottom name="jason" />
2、Bottom({name: "jason"})
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM