1穷当、setState是異步的提茁,如何合并多次setState,并且都生效
this.setState((state, props) => {...})
傳遞函數(shù)即可馁菜,state,props參數(shù)是可以拿上上一次的茴扁。當(dāng)然你也可以使用回調(diào),不過嵌套多了的話汪疮,你懂的
this.setState({...}, () => {
this.setState({...})
})
2峭火、react-hooks中如何拿到上一次的值
function App() {
let [count, setCount] = useState(0)
let lastState = useRef(count)
let plus = () => {
lastCount.current = count
console.log(lastCount.current) // 獲得count上一次的值
setCount(count + 1)
}
return (
<>
<p>{count}</p>
<button onClick={plus}>+</button>
</>
)
}
3智嚷、react-hooks如何模擬從前的生命周期
useEffect(() => {
// do...
return () => {} // return一個函數(shù)模擬componentWillUnmount
}, []) // 傳入空數(shù)組模擬componentDidMount