reactjs - hide and show external components in react
问题描述
I am newbie in react and I have some trouble that I'd like to solve. I would like to know how can I show and hide react components before and after to do a rest call. I have the follow component:
class Loading {
render(){
return (
<div >
<Modal isOpen={true} centered >
<ModalHeader>Loading...</ModalHeader>
<ModalBody >
<div align='center' className="mt-2 mb-2">
<Spinner style={{ width: '4rem', height: '4rem' }} color="primary" />
</div>
</ModalBody>
</Modal>
</div>
)
}
}export default Loading;
And I would like to show this component in other module before to call a rest api and hide this component after the data come. The ideia is some like this:
class List extends Component {
constructor(props) {
super(props)
this.state = {
show : false
}
}
// HERE I WOULD LIKE TO SHOW THE LOADING COMPONENT
callRestApi = () => {
axiosAuth.get(url, getConfig())
.then(response => {
console.log(response.data)
this.setState({
eventos: response.data
})
}).catch(error => {
console.log(error);
return null
});
// HERE I WOULD LIKE TO HIDE THE LOADING COMPONENT
}
render() {
return(
<div>
<Button className="mr-2" color="primary" size="sm" onClick={this.callRestApi}>List All</Button>
</div>
How can I do it?
解决方案
You can create state that dictates whether the loading spinner is visible or not. And append one last .then
in the promise chain to modify it.
class List extends Component {
constructor(props) {
super(props)
this.state = {
show : false,
loaderVisible: true
}
}
// HERE I WOULD LIKE TO SHOW THE LOADING COMPONENT
callRestApi = () => {
axiosAuth.get(url, getConfig())
.then(response => {
console.log(response.data)
this.setState({
eventos: response.data
})
}).catch(error => {
console.log(error);
return null
}).then(() => {
this.setState({loaderVisible: false });
});
}
render() {
return(
<div>
{
this.state.loaderVisible? <Loading /> : ''
}
<Button className="mr-2" color="primary" size="sm" onClick={this.callRestApi}>List All</Button>
</div>
Then utilize ternary syntax on the spinner to determine visibility.
推荐阅读
- javascript - Yaml 文件在 Gatsby Graphql 查询中返回 null
- python - 如何将具有 [1] (对象)等值的列转换为数值?
- python-3.x - 为什么我在提供的内容中收到 ValueError?
- c# - c# - 如何禁用按钮直到文本框在c#中不为空?
- asp.net-mvc - 如何在 Asp.Net MVC 中显示上周的数据
- javascript - 重用 Axis Scale 覆盖设置域
- c++ - C ++:array1 = array2 vs使用循环将array2的值分配给array1
- c# - 使用 AngleSharp 向 Microsoft 进行身份验证
- java - 为什么用轻微形式编写的 2 个相同的数字会在 Java 中产生 2 个不同的结果
- c# - Mathf.SmoothDamp 立即发生(Unity 3d)