【发布时间】:2021-09-26 04:03:56
【问题描述】:
当我尝试运行此代码并显示以下错误时。
警告:无法在尚未安装的组件上调用 setState。这是一个无操作,但它可能表明您的应用程序中存在错误。而是直接分配给this.state 或在Api 组件中定义具有所需状态的state = {}; 类属性。
我应该怎么做才能解决这个问题?
class Api extends Component {
constructor(props){
super(props)
this.state = {
data: [],
}
}
async componentDidMount(){
this.apiCall()
}
async apiCall() {
let resp = await fetch(URL)
let respJson = await resp.json()
this.setState({data:respJson.data.statistics})
}
}
export default function App(){
const api = new Api()
api.componentDidMount()
return (
<View>
<ScrollView style={styles.center}>
<Text>{api.state.data.time}</Text>
</ScrollView>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
padding: 20,
alignItems: 'center',
padding: 15,
},
title: {
padding: 30,
},
})
使用 Federkun 解决方案后,我得到了这个新错误,我对 JS 很陌生,所以我有点迷路。
我尝试使用异步函数,但一直显示错误。
Failed building JavaScript bundle. SyntaxError:
C:\Users\yup\Documents\GitHub\LEARN_REACT\App.js: Unexpected reserved word 'await'. (54:19) 52 | 53 | React.useEffect(() => { > 54 | let resp = await fetch(URL) | ^ 55 | let respJson = await resp.json() 56 | setData({data:respJson.data.statistics})
【问题讨论】:
标签: javascript react-native setstate