首页 > 解决方案 > 如何使用钩子和等待确保状态永远不会为空?

问题描述

我正在使用 acios 从 API 获取数据并更新我的钩子的值。初始值设置为空对象。我认为如果我在 axios 请求之前使用“等待”,那么在获取请求并设置新值之前,该函数将不会进行。

不幸的是,这并不总是发生,即使在应该等待 axios get-request 之后,“值”有时也会保持空白。

如何确保代码中的值 os mever "{}"?我认为“等待”应该解决这个问题,但事实并非如此。

import { Grid, Hidden } from '@material-ui/core';
import Link from '@material-ui/core/Link';
import ProjectInformation from '../../projects/components/ProjectInformation';
import axios from 'axios';

const style = {
    textAlign: 'left',
    float: 'right',
    position: 'fixed',
};

export default function ProjectPage(props) {
    const propsId = props.match.params.id;

    const [values, setValues] = useState({});
    useEffect(() => {
        getProjectById();
    }, []);

    const getProjectById = async () => {
        const { data } = await axios.get(`http://localhost:9000/projects/${propsId}`);
        setValues(data);
    };

    console.log('values are', values);

    return (
        <Grid container spacing={3}>
            <Hidden smDown>
                <Grid item sm={2}>
                    <div style={style}>
                        <Link href="#anchor1">Project Information</Link>
                        <br />
                        <Link href="#anchor2">Fieldwork Information</Link>
                        <br />
                        <Link href="#anchor3">Personell & Institutions</Link>
                        <br />
                        <Link href="#anchor4">Project Updates</Link>
                        <br />
                        <Link href="#anchor5">Datasets</Link>
                        <br />
                        <Link href="#anchor6">Publications</Link>
                    </div>
                </Grid>
            </Hidden>
            <Grid item xs={12} sm={10} style={{ borderLeft: '1px solid #dddddd' }}>
                <Grid item>
                    <div id="anchor1">
                        <ProjectInformation props={values} />
                    </div>
                </Grid>
                <Grid item>
                    <div id="anchor2">
                        <p>test</p>
                    </div>
                </Grid>
                <Grid item>
                    <div id="anchor3">
                        <p>test</p>
                    </div>
                </Grid>
                <Grid item>
                    <div id="anchor4">
                        <p>test</p>
                    </div>
                </Grid>
                <Grid item>
                    <div id="anchor5">
                        <p>test</p>
                    </div>
                </Grid>
                <Grid item>
                    <div id="anchor6">
                        <p>test</p>
                    </div>
                </Grid>
            </Grid>
        </Grid>
    );
}

标签: reactjsaxiosreact-hooks

解决方案


据我所知,每当一个 React 组件被引导时,如果你用一些值定义状态,即:this.state = {something: "something else"};那么它在初始化时就具有该状态。如果您的状态数据依赖于异步请求,则初始状态不会具有该值,我不认为仅使用async并且await会阻止这种情况,因为 React 直到组件安装后才会运行代码。

从文档:

如果熟悉 React 类生命周期方法,可以将 useEffect Hook 视为 componentDidMount、componentDidUpdate 和 componentWillUnmount 的组合。


推荐阅读