期望在新代码中使用hooks
函数 + hooks = 有‘生命周期’的组件
与class的区别:
Hook 提供了强大而富有表现力的方式来在组件间复用功能,自定义hook
const [originData, setStateData] = useState(0);
const newData = originData * 2;
setStateData(newData);
//
useEffect(()=>{}, []) // 第一个参数是 回调函数,第二个参数是 依赖项。
// 回调函数 在组件第一次render和之后的每次update后运行,React保证在DOM已经更新完成之后才会运行回调
// 依赖项 当配置了状态依赖项后,只有检测到配置的状态变化时,才会调用回调函数。
// 数据获取,设置订阅以及手动更改 React 组件中的 DOM 都属于副作用
// 一些react class 生命周期的执行 ,在hooks中都可以使用 useEffect()实现
// 清除/不清除 定时器 ,订阅外部数据源 =》 清除
// 装饰器不可用于函数式组件,如果需要包裹,
// export default Form.create()(View)
Hooks 方法 对应 Class 生命周期
Class | Hooks |
---|---|
constructor | useState 初始化state |
getDerivedStateFromProps | useEffect + other(useState) |
shouldComponentUpdate | useMemo |
render | 函数本身 |
componentDidMount | useEffect + other |
componentDidUpdate | useEffect + other |
componentWillUnmount | useEffect + other |
componentDidCatch | 无 |
getDerivedStateFromError | 无 |
React 16.3新周期函数
componentWillReceiveProps(props) => UNSAFE_componentWillReceiveProps(props)
static getDerivedStateFromProps
:该函数在挂载阶段和组件更新阶段都会执行,即每次获取新的props
或 state
之后都会被执行,在挂载阶段用来代替componentWillMount
;在组件更新阶段配合 componentDidUpdate
,可以覆盖componentWillReceiveProps
的所有用法。
同时它是一个静态函数,所以函数体内不能访问 this
,会根据 nextProps
和 prevState
计算出预期的状态改变,返回结果会被送给 setState
,返回 null
则说明不需要更新 state
,并且这个返回是必须的。
componentWillReceiveProps(nextProps) {
const { value } = nextProps;
const { detail } = this.state;
if (JSON.stringify(value) == JSON.stringify(detail)) return;
this.setState({ detail: value }, () => {
this.calculateTotal();
});
}
---------> 16.3 新周期
static getDerivedStateFromProps(nextProps, prevState) {
const { value: detail } = nextProps;
// 当传入的type发生变化的时候,更新state
if (
JSON.parse(JSON.stringify(detail)) !==
JSON.parse(JSON.stringify(prevState.detail || []))
) {
return {
detail,
};
}
// 否则,对于state不进行任何操作
return null;
}
componentDidUpdate() {
this.calculateTotal();
}
-------> Hooks
const [detail, setDetail] = useState([]);
useEffect(() => {
setDetail(value);
calculateTotal(value);
}, [value]);
// 只要value有更新,就setDetail