我需要在setState完成后解析promise,但在react hooks中,setState(useState(没有回调函数。
React钩子版本的代码:
handleBeforeGetContent = () => {
return new Promise((resolve, reject) => {
this.setState({ key: 'updatedValue' }, () => resolve());
});
}
您可以在useEffect中使用异步函数,如下所示。
const [isLoadingComplete, setLoadingComplete] = React.useState(false);
React.useEffect(() => {
async function loadDataAsync() {
try {
await loadAsyncSomething();
} catch (e) {
console.warn(e);
} finally {
setLoadingComplete(true);
}
}
loadDataAsync();
}, []);
您可以使用useEffect作为useEffect中的参数,该函数绕过您想要观察的所需状态来运行每个状态更改。
React.useEffect(() => {
//your callback function can be executed here after the updatedValue updated
}, [updatedValue]);
您可以使用自定义useState挂钩在setState中使用回调
下面的代码演示了这一点。
const useStateWithCallback = (initialValue) => {
const cbRef = React.useRef();
const [state, setState] = React.useState(initialValue);
React.useEffect(() => {
if (cbRef.current) {
cbRef.current(); // calls the callback after setState has finished
cbRef.current = null; // reset for next cb
}
}, [state]);
const setStateWithCallback = (setter, cb) => {
if (cb) cbRef.current = cb; // save the cb to call after setState is finished in useEffect above.
if (typeof setter === "function") {
setState(setter(state));
} else {
setState(setter);
}
};
return [state, setStateWithCallback];
};
// usage
const Counter = (props) => {
const [count, setCount] = useStateWithCallback(0);
const [state, setState] = useStateWithCallback(null);
const incrementAndDoSomething = () => {
setCount((prev) => prev + 1, () => console.log('Do something when setState has finished'));
}
// your usecase
handleBeforeGetContent = () => {
return new Promise((resolve, reject) => {
setState({
key: 'updatedValue'
}, () => resolve());
});
}
return <h1 > {
count
} < /h1>;
}