更改与动画道具绑定的变量值后,activityIndicator 的可见性不会改变
Visibility of activityIndicator isn't changed after changing the value of variable which is bind with animating props
我需要在从服务器获取数据时显示加载指示器。为此,我添加了
<View>
<ActivityIndicator animating={this.state.isLoading} size="large" color="#0000ff" />
</View>
这里是我调用抓取函数的地方:
componentDidMount() {
this.state.isLoading = true;
const { getCities } = this.props;
getCities();
this.state.isLoading = false;
}
所以,我想在这个地方显示加载指示器(因为我更改了变量,这会影响加载指示器的可见性)但不幸的是没有任何反应。那么,这是什么原因,我该如何解决这个问题?
View
没有指定样式。
this.state={
isLoading : true
}
componentDidMount() {
const { getCities } = this.props;
setTimeout(() => {
getCities();
this.setState({isLoading: false})
}, 5000)
}
....
render() {
return this.state.isLoading === true ? (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<ActivityIndicator
size="large"
color="#0000ff"
/>
</View>
) : (
<View style={{ flex: 1 }}>
...
有一件事让我很困惑:
- 同步设置状态不是一个好习惯,你应该使用 setState 函数
我会重构如下:
displayLoading = () => {
this.setState({ isLoading: true })
}
closeLoading = () => {
this.setState({ isLoading: false })
}
fetchCities = async () => {
const { getCities } = this.props;
displayLoading()
await getCities()
closeLoading()
}
componentDidMount() {
this.fetchCities()
}
注意:对于这个解决方案,我认为你不需要 use/need redux :) 否则,我会建议 redux 和一个中间件来自动显示加载到所有 api fetch
我需要在从服务器获取数据时显示加载指示器。为此,我添加了
<View>
<ActivityIndicator animating={this.state.isLoading} size="large" color="#0000ff" />
</View>
这里是我调用抓取函数的地方:
componentDidMount() {
this.state.isLoading = true;
const { getCities } = this.props;
getCities();
this.state.isLoading = false;
}
所以,我想在这个地方显示加载指示器(因为我更改了变量,这会影响加载指示器的可见性)但不幸的是没有任何反应。那么,这是什么原因,我该如何解决这个问题?
View
没有指定样式。
this.state={
isLoading : true
}
componentDidMount() {
const { getCities } = this.props;
setTimeout(() => {
getCities();
this.setState({isLoading: false})
}, 5000)
}
....
render() {
return this.state.isLoading === true ? (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<ActivityIndicator
size="large"
color="#0000ff"
/>
</View>
) : (
<View style={{ flex: 1 }}>
...
有一件事让我很困惑: - 同步设置状态不是一个好习惯,你应该使用 setState 函数
我会重构如下:
displayLoading = () => {
this.setState({ isLoading: true })
}
closeLoading = () => {
this.setState({ isLoading: false })
}
fetchCities = async () => {
const { getCities } = this.props;
displayLoading()
await getCities()
closeLoading()
}
componentDidMount() {
this.fetchCities()
}
注意:对于这个解决方案,我认为你不需要 use/need redux :) 否则,我会建议 redux 和一个中间件来自动显示加载到所有 api fetch