我正在尝试使用axios调用API数据。我收到console.log的回复。尽管响应没有显示在屏幕上。真的卡住了。
export default class PrivacyPolicyScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: null,
}
}
componentDidMount () {
return fetch ('API', {
method: 'GET',
headers:{
'Content-Type': "application/json",
'x-api-key': 'KEy'
},
})
.then( (response)=> response.json() )
.then ( (responseJson) => {
console.log ("This is the response that should be in the app", {responseJson})
this.setState({
isLoading: false,
dataSource: responseJson.terms,
})
})
.catch((error) => {
console.log(error)
})
};
render () {
if (this.state.isLoading){
return (
<Text >Loading Privacy!!!!</Text>
)
} else {
let privpolicy = this.state.responseJson.map((val, key ) => {
return <View key={key}>
<Text >{val.dataSource}</Text>
</View>
})
return (
{privpolicy}
);
}
}
}
错误是TypeError: Cannot read property 'map' of undefined
第42行上的未定义对象。我已经尝试过componentWillMount
了几次。我真的很难在这里找到解决方案。
无法映射响应的原因是因为您没有收到能够映射它的数组(只能将.map与数组一起使用)。
因此,根据您的答案判断,您会收到一个字符串(文本),然后要显示该字符串。为此,您必须执行以下操作:
componentDidMount () {
return fetch ('API', {
method: 'GET',
headers:{
'Content-Type': "application/json",
'x-api-key': 'KEy'
},
})
.then( (response)=> response.json() )
.then ( (responseJson) => {
console.log ("This is the response that should be in the app", {responseJson})
this.setState({
isLoading: false,
dataSource: responseJson,
})
})
.catch((error) => {
console.log(error)
})
};
render () {
if (this.state.isLoading) {
return (
<Text >Loading Privacy!!!!</Text>
)
} else if (this.state.dataSource) {
return (
<View>
<Text>{this.state.dataSource}</Text>
</View>
)
}
return null;
}
我还为添加了另一张支票this.state.dataSource
,尽管这只是我个人喜欢做的事情,您可以将其删除。
这样尝试,然后告诉我是否可行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句