我正在尝试找到一种使用hooks来模拟this.setState({},() => {})
回调函数的方法。
我成功地创建了一个方法,模仿了useState
函数,但返回一个带有更新后数据的回调函数。
接收回调函数在状态更新后返回,可以从日志中看到,只有在出现console.log("App")
后,才会接收回调函数,这类似于如果使用this.state
和callback
的行为。
问题是,在修改过的setState
的callback
内部,即使在更新应用程序后调用,我也无法看到状态的更新,也就是说,如果我尝试打印它,我不会看到更新的状态。
您认为是否有解决方案,能够做些什么来查看其更新。
const { useState, useRef, useEffect } = React;
function useStateCallback(initialState) {
const [state, setState] = useState(initialState);
const cbRef = useRef(null);
useEffect(() => {
if (cbRef.current) {
cbRef.current(state);
cbRef.current = null;
}
}, [state]);
return [
state,
(value, cb) => {
cbRef.current = typeof cb === "function" ? cb : null;
setState(value);
}
];
}
const App =() => {
const [stateObj, setStateObj] = useStateCallback({
name: "James",
surname: "Bond",
number: 7
});
const { name, surname, number } = stateObj;
useEffect(() => {
//console.log("componentDidMount", stateObj);
//console.log("componentDidMount2", stateObj);
//console.log("useEffect", stateObj);
}, []);
const change = () => {
//console.log("componentDidMount", stateObj);
setStateObj(
previousValue => ({
...previousValue,
name: "Arthur",
surname: "Conan",
number: previousValue.number + 14
}),
res => {
console.log("Res:", res, stateObj);
}
);
//console.log("componentDidMount2", stateObj);
};
console.log("App", stateObj);
return (
<div>
Name: {name}
<br />
Surname: {surname}
<br />
Number: {number}
<br />
<button onClick={change}>Change</button>
<button onClick={() => console.log(stateObj)}>Render</button>
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
useEffect(() => { /* code here */ }, [stateObj]);
م€‚https://codesandbox.io/s/ecstatic-sun-exww1 - user5734311