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;
}
}
我有一个可能适合您的解决方法。
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;
}
}