我试图查询API以使用本机应用程序中的数据,但遇到了访问我在状态中存储的数据的问题。基本上,我试图访问存储在该州的市场对象。如果我检查状态,我会看到市场对象已正确设置。但是,只要我尝试对market对象执行任何操作,我就会遇到错误Cannot read property 'markets' of null
。
为什么会发生这种情况?如何解决此问题?
我在下面列出了导致问题的代码。我很感激任何建议。
export default class cryptoTracker extends Component {
constructor(props) {
super(props);
this.opts = {
baseUrl: 'https://bittrex.com/api/v1.1',
apikey: 'APIKEY',
apisecret: 'APISECRET',
};
this.updateMarkets();
}
updateMarkets(){
axios.get(this.opts.baseUrl + '/public/getmarkets').then((response) => {
this.setState({'markets' : response.data.result});
}
).catch((error) => {
console.log(error.name)
console.log("Error");
});
}
render() {
console.log("The state is below");
console.log(this.state);
//This line causes the issue
console.log(this.state.markets);
return(
<View>
</View>);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('cryptoTracker', () => cryptoTracker);
答案 0 :(得分:1)
原因是,您没有在state
中定义constructor
变量。 Api调用异步,因此当您获取数据并执行setState
之后,只有state
可用(之前state
将为null
),渲染将在此之前执行,当它将尝试访问值this.state.makers
时,它会抛出错误:
无法阅读房产&#39;市场&#39;为null
的变化:
1。定义state
对象并在其中定义makers
,如下所示:
constructor(props) {
super(props);
this.state = {
makers: {}
}
this.opts = {
baseUrl: 'https://bittrex.com/api/v1.1',
apikey: 'APIKEY',
apisecret: 'APISECRET',
};
}
2。使用componentDidMount生命周期方法并在其中执行api调用,如下所示:
componentDidMount(){
this.updateMarkets();
}
componentDidMount()在组件出现后立即调用 安装。需要DOM节点的初始化应该放在这里。如果你 需要从远程端点加载数据,这是一个好地方 实例化网络请求。在这种方法中设置状态会 触发重新渲染。
3。组件的名称必须以大写字母开头,因此请使用 CryptoTracker 而不是 cryptoTracker 。