添加回调函数以挂钩setState

时间:2019-08-27 11:06:27

标签: reactjs react-hooks

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;
        }
     }

1 个答案:

答案 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;
    }
 }