Hooks setState需要同步更新,以便应用程序正常运行。在类组件中,我们可以像this.setState({},()=>{})
那样对其进行回调,但是如何使用钩子进行回调。
尝试异步并等待:
const [profilePicValidation, setprofilePicValidation] = useState("")
async function mimeType(headerString, blob){
switch (headerString) {
case "ffd8ffe2":
await setprofilePicValidation(true);
console.log("state",profilePicValidation);
return true;
break;
default:
await setprofilePicValidation(false);
console.log("state",profilePicValidation);
break;
}
}
原始
: const [profilePicValidation, setprofilePicValidation] = useState("")
function mimeType(headerString, blob){
switch (headerString) {
case "ffd8ffe2":
setprofilePicValidation(true);
console.log("state",profilePicValidation);
return true;
break;
default:
setprofilePicValidation(false);
console.log("state",profilePicValidation);
break;
}
}
答案 0 :(得分:2)
我有一种解决方法,可能对您有用。
import {useState, useEffect} from 'react'
const [profilePicValidation, setprofilePicValidation] = useState("")
useEffect(() => {
// updated profilePicValidation
console.log('state', profilePicValidation)
}, [profilePicValidation])
function mimeType(headerString, blob){
switch (headerString) {
case "ffd8ffe2":
setprofilePicValidation(true);
return true;
break;
default:
setprofilePicValidation(false);
break;
}
}