React钩子没有使用async await设置对象状态。始终未定义

问题描述 投票:0回答:1

为一个名为updateSOR的组件写了一个UpdateSOR函数,该组件可以从之前的一个名为SOR的页面导航。

UpdateSOR是一个表单,应该由api预先填写。因此,如果用户直接来到这个页面或从上一个页面,我在useEffect中写了一个api调用,并设置了const [SOR]的值,该值将在页面加载时被用于表单中,以预先填充它。

 export default function UpdateSOR(props) {
    const [SOR, setResult] = React.useState({}); // empty object
    useEffect(() => {
        const getSOR = async () => {
            console.log("Inside async");

            await QueryService.getSOR(props.match.params.sorID).then(
              (result) => {
                console.log("Inside await then");
                if (result.status === 200) {
                  setResult(result.data.data.dataItems); // set the value for SOR here 
                  console.log("result.data.data.dataItems" ,result.data.data.dataItems);
                }
              }
            ).catch(error => {
              console.error(error);
            });
            getSOR();

          }
      }, []);


console.log("Value of SOR" , SOR) // value of sor is empty object which was during initialization and SOR is not coming from the api written above in useEffect :(

 return (

    <Container fluid={true} className="pt-4 pb-4 pl-0 pr-0">
        <Row className={`align-items-center ${classes.header}`}>
            <Col lg="10">
                <h4 className="pl-4">Form SOR</h4>
            </Col>
            <Col lg="1">
                <Button type="submit" variant="contained" color="primary" onClick={handleSave} className="mr-3 float-right">
                    Save
                    </Button>
            </Col>
            <Col lg="1">
                <Button variant="contained" color="primary" onClick={handleCancel} className="mr-3 float-right">
                    Cancel
                    </Button>
            </Col>
        </Row>
        <form className={`${classes.form} ${classes.body}`} noValidate autoComplete="off">
            <Row>
                <Col lg="2" onChange = {(event) => setSelectedSorName(event.target.value)}>
                    <CommonInput
                        id="sor_name"
                        label="SOR Name"
                        defaultValue={SOR.SOR_NAME}
                        disabled={false}
                        multiline={false}
                        rows="1" />
                </Col>
            </Row>
)

当我试图控制台.记录SOR的值时,我没有从api.Am我做任何错误。我想有一种可能是我没有正确使用async await。这是我的queryService文件,我在这个updateSOR文件中调用这个api的地方

function getSOR(id) {
    if(id) {
        return axios.get(`${Constants.API_URL}/SOR?id=${id}`);
    } else {
        return axios.get(`${Constants.API_URL}/SOR`);
    }

}
reactjs async-await react-hooks setstate
1个回答
0
投票

你不能使用async await和then catch。

你的getSOR是async函数,你不能使用.then .catch块。

做到这一点,而不是。

const[SOR, setSOR] = useState();
    useEffect(() => {
       const fetchSOR = async () => {
           try {
               const {data} = await QueryService.getSOR(id);
               setSOR(data);
           } catch(e) {
               // if response is rejected this will execute
               console.log(error);
           }
       }
       fetchSOR();

    }, []);
© www.soinside.com 2019 - 2024. All rights reserved.