Reactjs 如何确保钩子和等待状态永远不为空?
我正在使用acios从API获取数据并更新挂钩的值。初始值设置为空对象。我认为,如果在axios请求之前使用“wait”,则在获取请求并设置新值之前,函数将不会进行 不幸的是,这种情况并不总是发生,即使在本应等待axios get请求之后,“值”有时也会保持为空 如何确保代码中的值为os mever“{}”?我原以为“等待”可以解决这个问题,但事实并非如此Reactjs 如何确保钩子和等待状态永远不为空?,reactjs,axios,react-hooks,Reactjs,Axios,React Hooks,我正在使用acios从API获取数据并更新挂钩的值。初始值设置为空对象。我认为,如果在axios请求之前使用“wait”,则在获取请求并设置新值之前,函数将不会进行 不幸的是,这种情况并不总是发生,即使在本应等待axios get请求之后,“值”有时也会保持为空 如何确保代码中的值为os mever“{}”?我原以为“等待”可以解决这个问题,但事实并非如此 import { Grid, Hidden } from '@material-ui/core'; import Link from '@m
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>
);
}
从'@material ui/core'导入{Grid,Hidden};
从“@material ui/core/Link”导入链接;
从“../../projects/components/ProjectInformation”导入项目信息;
从“axios”导入axios;
常量样式={
textAlign:'左',
浮动:'对',
位置:'固定',
};
导出默认功能项目页面(道具){
const propsId=props.match.params.id;
const[values,setValues]=useState({});
useffect(()=>{
getProjectById();
}, []);
const getProjectById=async()=>{
const{data}=wait axios.get(`http://localhost:9000/projects/${propsId}`);
设定值(数据);
};
console.log('值是',值);
返回(
项目信息
实地调查资料
人事与机构
项目更新
数据集集合
出版物
试验
试验
试验
试验
试验
);
}
据我所知,如果您使用一些值定义状态,则每当React组件启动时,即:this.state={something:“something other”}代码>则它在初始化时具有该状态。如果state的数据依赖于异步请求,那么初始状态就不会有该值,而且我不认为仅仅使用async
和await
就可以防止这种情况,因为React在组件装载之后才运行代码
从文档中:
如果您熟悉React类生命周期方法,
您可以将useEffect挂钩视为componentDidMount,
componentDidUpdate和componentWillUnmount组合在一起
您可以执行以下任一操作:
数据?设置值(数据):空代码>
或
数据和设置值(数据)代码>这应该会有帮助:如果(数据){setValues(数据);}
一切看起来都很可靠,您可以创建一个模拟问题的JSFIDLE吗?