什么是props
用来传递数据,存储数据的数据变量,
props 的改变会导致ui 的重写渲染,具有参数自动封装对象接口(对外),如父组件的数据传递,主要用于函数组件无状态组件(包括常量和函数回调)
- 函数组件:函数组件与类组件的区别
函数组件使用 React Hooks(如 useState 和 useEffect)来管理状态和生命周期,无需继承
- 类组件:类组件使用 ES6 类定义
类组件使用 this.state 和生命周期方法(如 componentDidMount、componentDidUpdate 和 componentWillUnmount)来管理状态和生命周期,主要继承component,react
props尽量不要修改,数据流规定是单向的(可读性),防止数据的错乱导致未知bug,如组件内修改了props 的数据导致父数据的错乱,
什么是state
组件内部数据的数据集合,state 改变通常伴随的着ui的改变
- setState:在react 中是异步的
延迟更新,放到state 的队列内,一次执行多个,从而减少DOm 的更新
- setState:同步
js 原生的一些方法如:setTimeOut
this 的使用
这个和Java 很相似谁调用指向谁(在全局对象中指向的的是windows)
- 显性使用
绑定state 和组件函数 this 指向当前组件对象
constructor(props) {
super(props);
this.state = { count: 0 };
// 绑定事件处理函数
this.increment = this.increment.bind(this);
}
increment() {
this.setState((prevState) => ({
count: prevState.count + 1
}));
}
- 隐形使用
可以做到隐形,这依赖箭头函数的词法作用域:不会创建自己的 this 上下文。相反,箭头函数会捕获其定义时所在的上下文的 this 值,并且在其整个生命周期内保持这个值不变,我们可以理解为没有函数作用域的函数
import React, { Component } from 'react';
class Counter extends Component {
state = { count: 0 };
increment = () => {
this.setState((prevState) => ({
count: prevState.count + 1
}));
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
export default Counter;
使用中如何选择 props or state
- 让组件尽量少状态
主要是ui展示,少量交互使用props,常用于父组件
- ui 变化频繁
随着时间和时机的变化ui状态变化使用state常用于类组件
- 数据范围
数据对外时,选择props,state相当于内部变量,私有变量,用于内部ui和数据状态的更新