import React from 'react';
import { Card, Text } from "react-native-paper";
import {
SafeAreaView,
} from "react-native";
class Hnews extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
isLoaded: false,
};
}
// Function to collect data
async componentDidMount() {
await fetch(
"https://hacker-news.firebaseio.com/v0/item/26061935.json?print=pretty"
)
.then((res) => res.json())
.then((json) => {
this.setState({
isLoaded: true,
data: json.data,
});
console.log("Json", JSON.stringify(json));
});
}
render() {
return (
<SafeAreaView>
<Card>
{this.state.newdata.map((item) => {
<Text>{item.title}</Text>
})}
</Card>
</SafeAreaView>
);
}
}
export default Hnews;
我正在做一個黑客新聞克隆,我正在獲取 API 并顯示它,但給出了錯誤“無法讀取未定義的屬性(讀取‘地圖’)”。我已經看到了很多此類問題的答案,并更改了我的解決方案,但沒有任何效果。
uj5u.com熱心網友回復:
正如我所看到的,this.state.newdata.map((item)您正在嘗試映射,this.state.newdata并且如果您注意,您正在newdata通過呼叫someMethod您從未在應用程式中呼叫過的方法將資料存盤到狀態,因此newdata狀態始終為空,以下內容應該為您解決:
import React from 'react';
import { Card, Text } from "react-native-paper";
import {
SafeAreaView,
} from "react-native";
class Hnews extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
isLoaded: false,
};
}
// Function to collect data
async componentDidMount() {
await fetch(
"https://hacker-news.firebaseio.com/v0/item/26061935.json?print=pretty"
)
.then((res) => res.json())
.then((json) => {
this.setState({
isLoaded: true,
data: json.data,
});
console.log("Json", JSON.stringify(json));
});
}
render() {
return (
<SafeAreaView>
<Card>
{this.state.data.map((item) => {
<Text>{item.title}</Text>
})}
</Card>
</SafeAreaView>
);
}
}
export default Hnews;
如果你注意你正在獲取的資料,你就會明白那里沒有可映射的專案,你只能映射 kids

uj5u.com熱心網友回復:
您的代碼片段似乎不完整。但是,如果在代碼中的任何地方呼叫函式 someMethod ,它可能是罪魁禍首。
在其中,您通過為其分配 JSON.stringify 輸出將狀態的 newdata 欄位設定為字串。一旦它是一個字串,就沒有可以呼叫它的 map 函式,我假設這就是您收到未定義錯誤的原因。它需要是一個專案陣列才能使用 map 函式。
如果您完全洗掉 newdata 并且只洗掉參考資料,它應該可以作業,假設回應資料是一個陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/398806.html
標籤:javascript 数组 反应 反应原生 接口
