reactjs - 如何使用钩子和等待确保状态永远不会为空?
问题描述
我正在使用 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>
);
}
解决方案
据我所知,每当一个 React 组件被引导时,如果你用一些值定义状态,即:this.state = {something: "something else"};
那么它在初始化时就具有该状态。如果您的状态数据依赖于异步请求,则初始状态不会具有该值,我不认为仅使用async
并且await
会阻止这种情况,因为 React 直到组件安装后才会运行代码。
从文档:
如果熟悉 React 类生命周期方法,可以将 useEffect Hook 视为 componentDidMount、componentDidUpdate 和 componentWillUnmount 的组合。
推荐阅读
- java - java.utill.Time 和 java.sql.time 有什么区别
- ios - APNs 身份验证密钥是否会过期?
- android - 识别被触摸的视图
- ionic-framework - 无法使用 Ionic 3 使用无限滚动
- machine-learning - 如何在生产流程中不断提高tensorflow对象检测模型的准确率?
- javascript - 多个类似的“选择选项”ID,动态 Javascript 代码
- r - R:快速生成部分序列
- sql-server - 如何获取存储过程返回的值并将其用于 INSERT INTO... SELECT... 语句
- android - 如何检查monkeyrunner是否发生崩溃
- reactjs - Gatsby.js 和 redux-promise 中间件