我正在使用API获取以下对象,然后将其存储为状态:
"DIA": Object {
"c": 265.64,
"h": 266.31,
"l": 264.35,
"o": 264.77,
"t": 1595822400,
"v": 1544226,
},
"IWM": Object {
"c": 146.515,
"h": 147.23,
"l": 145.39,
"o": 146.19,
"t": 1595822400,
"v": 6815926,
},
"QQQ": Object {
"c": 257.66,
"h": 259.45,
"l": 256.445,
"o": 257.36,
"t": 1595822400,
"v": 17509982,
},
"SPY": Object {
"c": 322.16,
"h": 322.97,
"l": 320.775,
"o": 321.63,
"t": 1595822400,
"v": 22930992,
},
如果我通过执行console.log(this.state.SPY)
来控制台登录“ SPY”,则会得到
Object {
"c": 322.21,
"h": 322.97,
"l": 320.775,
"o": 321.63,
"t": 1595822400,
"v": 23059231,
}
,如果我通过执行console.log(this.state.SPY)
在“ SPY”中登录日志“ c”,则会得到“ 322.21”。但是,如果我尝试访问这些对象中的任何一个中的“ c”并通过执行<Text>{this.state.SPY.c}</Text>
将其打印到屏幕上,则会收到以下错误undefined is not an object (evaluating 'this.state.SPY.c')
。我认为我的问题是在尝试使用我的API定义{this.state.SPY.c}之前呈现文本。有没有办法让它等待我的API调用完成并且信息处于状态然后打印呢?抱歉,因为我刚刚研究过,并且不了解其他解决方案,因为我对本机非常陌生,所以是否曾有人问过我。
这是我的代码(显然还有更多,但是我保持了相关性):
class DashboardScreen extends React.Component {
static navigationOptions = {
title: 'Dashboard'
};
constructor(props) {
super(props)
}
componentDidMount() {
const alpaca = alpacaAPI()
symbols.map((symbol) =>{
alpaca.getMarket(symbol).then((response) => {
let state = this.state
state[symbol] = response.data[symbol][0]
this.setState(state)
})
})
}
render() {
return <View>
<Text>{this.state.DIA.c}</Text>
<Text>{this.state.IWM.c}</Text>
<Text>{this.state.QQQ.c}</Text>
<Text>{this.state.SPY.c}</Text>
</View>
}
}