1、useState
class组件中this.setState更新是state是合并, useState中setState是替换
2、useEffect
import { useState, useEffect } from 'react'
const Test = () => {
const [count1, setCount1] = useState(0);
useEffect(() => {
console.log('useEffect触发了')
return () => { // 清理副作用 }
});
return (
<>
<h1>count1:{count1}</h1>
<button onClick={() => setCount1(count1 + 1)}>count1+1</button>
</>
);
}
export default Test
3、useContext:跨组件共享数据
import React, { useContext, useState } from 'react';
const TestContext = React.createContext();
const Parent = () => {
const [value, setValue] = useState(0);
return (
<div>
{(() => console.log("Parent-render"))()}
<button onClick={() => setValue(value + 1)}>value + 1</button>
<TestContext.Provider value={value}>
<Child1 />
<Child2 />
<Child3 />
</TestContext.Provider>
</div>
);
}
// 在class组件中
static childContextTypes = {
value: PropTypes.number
}
getChildContext () {
return { value: this.state.value }
}
# useContext
const Child1 = () => {
const value = useContext(TestContext);
return (
<div>
{(() => console.log('Child1-render'))()}
<h3>Child1-value: {value}</h3>
</div>
);
}
# consumer
const Child2 = () => {
return (
<TestContext.consumer>
{value => <p>Child2: - {value}</p>}
</TestContext.consumer>
);
}
# contextType
class Child3 extends React.Component {
static contextType = TestContext
render () {
const value = this.context
return (
<h3>Child3-value: {value}</h3>
)
}
}
export default Parent
4、useCallback:性能优化
// useCallback(回调函数,[依赖值])
const handleClick = useCallback(()=> {
// 做一些事
}, [value]);
5、useMemo:性能优化
// useMemo(回调函数,[依赖值])
useMemo(() => { // 做一些事情 },[value]);
- useCallBack 一个缓存的回调函数;父组件更新时,通过props传递给子组件的函数也会重新创建
- useMemo 一个缓存的值;组件更新时,一些计算量很大的值也有可能被重新计算,这个时候就可以使用 useMemo 直接使用上一次缓存的值
import React, { useState, useCallback, memo } from 'react';
const Parent = () => {
const [value1, setValue1] = useState(0);
const [value2, setValue2] = useState(0);
const handleClick1 = useCallback(()=> {
setValue1(value1 + 1);
}, [value1]);
const handleClick2 = useCallback(()=> {
setValue2(value2 + 1);
}, [value2]);
return (
<>
{(() => console.log("Parent-render"))()}
<h3>{value1}</h3>
<h3>{value2}</h3>
<Child1 handleClick1={handleClick1} />
<Child2 handleClick2={handleClick2} />
</>
);
}
const Child1 = memo(props => {
return (
<div>
{(() => console.log("Child1-render"))()}
<button onClick={() => props.handleClick1()}>value1 + 1</button>
</div>
);
});
const Child2 = memo(props => {
return (
<div>
{(() => console.log("Child2-render"))()}
<button onClick={() => props.handleClick2()}>value2 + 1</button>
</div>
);
});
export default Parent