[英]React Native can not render fetched data. Throws Undefined is not an Object
我目前正在研究本機項目。
我在componentDidMount函數中使用axios獲取數據,但是數據是SOAP方式。 因此,我要使用xml-js包將數據xml更改為json。
這是我的狀態;
state = {
contacts: [],
isLoading: true
}
這是我的componentDidMount()函數;
componentDidMount() {
xmls = 'my envelope to server.';
Axios.post('my url goes here.', xmls, {
headers: {
'Content-Type': 'text/xml; charset=UTF-8',
'Authorization': 'my key',
'SOAPAction': "my action"
}
}).then(response => {
return response.data;
}).then((res) => {
const options = {
compact: true,
ignoreDeclaration: true,
spaces: 4,
ignoreAttributes: true,
textFn: this.removeJsonTextAttribute,
elementNameFn: function (val) { return val.replace('SOAP-ENV:', '').replace('ns:', ''); } //removes 'SOAP-ENV: and ns: tags from SOAP data.
}
// converting string xml to string json.
let xmlToJSON = convert.xml2json(res, options);
// converting string to json with JSON.parse()
return contactsObj = JSON.parse(xmlToJSON);
}).then((fin) =>{
this.setState({contacts: fin, isLoading: false});
}).catch(err => {
console.warn('Error', err);
});
}
這是我的渲染功能;
render() {
let arr = [];
arr.push(this.state.contacts);
let {isLoading} = this.state;
let res = arr.map((item, i)=> {
return <AnnounceList headLine = {item[0].Envelope.Body.a.b.c[i]} />
});
return (
<View style = {{flex: 1}}>
<TopBar name={"Iletisim"} bColor={"#29303c"} miniLogo={require('../../../assets/pictures/Ikon07-tip2-0.png')} />
<Spinner loading = {isLoading} color = '#29303c'>
<ScrollView>
{res}
</ScrollView>
</Spinner>
</View>
);
}
為了渲染數據,我創建了一個數組實例並將狀態聯系人數據推送到該實例。 但是,當我嘗試從數組中選擇數據時,拋出未定義的錯誤不是對象錯誤。 數據在信封之前有效,但是在信封之后,它會引發錯誤。 我不明白為什么要扔? 任何想法。 感謝您的所有貢獻。
補充信息!
在我的狀態下,聯系人是一個數組。 但是在我的渲染函數中,當我嘗試使用this.state.contacts.map()
它使我無法定義是不起作用的,因此我使用console.log(typeof this.state.contacts)
檢查了它的類型,它返回了對象。 為什么它成為對象? 難道它不能作為數組保留嗎?
我認為問題出在這里
let res = arr.map((item, i)=> {
return <AnnounceList headLine = {item[0].Envelope.Body.a.b.c[i]} />
});
您正在遍歷所有物品,正在拿物品[0]? 為什么? 然后,您將i作為元素的索引。 為什么不使用物品? 添加類似:
let res = arr.map((item, i)=> {
return <div>JSON.stringify(item)</div>
});
將幫助您進行調試。 您還可以使用以下方法使json更美觀:
return <div><pre>{JSON.stringify(item, null, 2) }</pre></div>;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.