函数组件:
类似这种
function ControlWarning(){
const [count, setCount ] = useState(0);
return <div>数量: {this.state.count} </div>
}
该函数是一个有效的 React 组件,因为它也是接收唯一带有数据的 “props”(代表属性)对象与并返回一个 React 元素。这类组件被称为“函数组件”,因为它本质上就是 JavaScript 函数。
类组件:
使用 ES6 的 class 来定义组件
class FileName extends Component {
constructor(props) {
super(props);
this.state = {
count:0
};
}
render(){
return <div>数量: {this.state.count} </div>
}
}
注:
(1)函数组件本质是函数,没有 state 的概念的,因此不存在生命周期一说,仅仅是一个 render 函数而已。
(2)Hooks 组件(使用了Hooks的函数组件)有生命周期,而函数组件(未使用Hooks的函数组件)是没有生命周期的
1. 初始化:
类组件的
this.state = {
count:0
};
函数组件
const [count, setCount ] = useState(0);
2. 改变count变量的值:
类组件:
this.setState({
count:5
});
函数组件:
setCount (5);
3. 使用count
类组件:this.state.count
函数组件:直接count
4. 生命周期
Hooks 组件(使用了Hooks的函数组件)有生命周期,而函数组件(未使用Hooks的函数组件)是没有生命周期的。
useEffect(() => {
console.log('count', count);
return () => {
console.log('count clear', count);
};
}, [count] );
1)函数组件里的componentWillMount、componentDidMount 挂载函数 在函数组件里相当于useEffect;
2)函数组件里的componentWillReceiveProps 挂载函数 在函数组件里相当于useEffect(() => { }, [count] );( 参数依赖 无[]只加载1词,[]会一直加载,[count] count只要变化就加载一次);
3)函数组件里的componentWillUnmount 挂载函数 在函数组件里相当于useEffect里的return函数。