javascript - 条件渲染显示两个组件
问题描述
我有两个要根据状态条件渲染的组件,但我遇到了一个问题,即在显示正确组件之前的一瞬间显示了错误的组件。
异步获取数据:
const [test, setTest] = useState();
const [loading, setLoading] = useState();
const [error, setError] = useState();
const fetchData = async () => {
console.log("running");
setLoading(true);
setError(false);
try {
const result = await axios(
"https://jsonplaceholder.typicode.com/posts/props.selectedId" // Is dynamic and changes on user click
);
setTest(result.data);
} catch (error) {
if (error.response.status == 404) {
setError(error);
setTest(null);
}
}
setLoading(false);
};
渲染:
return (
<div className={classes.root}>
{!loading && !error && test? (
<div>
<Card className={classes.card}>
<CardContent>
<Title>Adattributes</Title>
<Typography variant="h6" component="h1">
name
</Typography>
<Grid container spacing={3}>
<Grid item xs={3}>
<Typography variant="subtitle2" component="h1">
address
</Typography>
{test.title}
</Grid>
</Grid>
</CardContent>
<CardActions>
<Component1
value={test}
setTest={setTest}
/>
</CardActions>
</Card>
</div>
) : (
<Component2 setTest={setTest} />
)}
</div>
);
});
我在条件渲染上做错了吗?还是与获取异步有关?
解决方案
在第一行中,您使用没有初始状态的useState钩子,因此您的状态变为未定义(请记住,未定义是假值)。
const [test, setTest] = useState();
您应该为test设置初始状态,或者更改渲染组件的条件。
推荐阅读
- java - 为什么我的加法应用给出了错误的答案?
- vue.js - 如何将不同文件中的 ipcMain.on() 函数与 main.js 分开
- html - GatbysJS 排版 - AvenirNext - 不适用于 Windows / Linux
- android - INFO 暂时找不到测试类 SampleTest 正在跳过
- python - 如何修复 Heroku 上的 ImportError "_psutil_linux"
- angular - 无法获得 Textarea 的高度
- azure-active-directory - 为多个应用程序/环境配置 adal.js
- ruby - selenium/webdriver/firefox/binary.rb:134:in `path': 无法修改冻结字符串 (FrozenError)
- vue.js - Vue Slider Component - 同时启用拖尾和点击更新
- c# - 在 dotnet-core 控制台应用程序和常规 winforms 应用程序之间进行通信的最佳方式