我需要创建一个像this.setState这样的钩子,但我不知道如何在this.setState中实现类似回调的功能。你有什么想法吗?
import React, { useState } from 'react';
const useSetState = (initialState) => {
const [state, setState] = useState(initialState)
const setPartialState = (stateToSet, callback) => {
console.log('stateToSet: ', stateToSet);
console.log('callback: ', callback);
if (typeof stateToSet === 'function') {
setPartialState(stateToSet(state));
} else if (typeof state === 'object' &&
typeof stateToSet === 'object' &&
!Array.isArray(state) &&
!Array.isArray(stateToSet)
) {
setState({ ...state, ...stateToSet });
} else {
setState(stateToSet);
}
}
return [state, setPartialState]
}
const App = () => {
const [count, setCount] = useSetState(0);
const checkCount = () => {
if (count === 10) {
console.log('Booooom!');
}
}
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => setCount((count + 1, checkCount))}>Add</button>
</div>
);
}
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
在使用 React钩子时,与使用基于类的 React 组件相比,您需要使用不同的思维方式。
如果你想在计数更改为 10 时做某事,你应该在 useEffect 钩子中做。
const App = () => {
const [count, setCount] = useState(0);
useEffect(() => {
if (count === 10) {
console.log('Booooom!');
}
}, [count])
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => setCount(count + 1)}>Add</button>
</div>
);
}