[英]React Native fetch data from Express.js server
編輯:這是通過切換到其他Android手機模擬器來解決的
我正在嘗試創建一個簡單的React Native應用程序,該應用程序首先會從Express后端獲取一個json文件。
后端:
...data to be fetched up here in a dictionary
//Enable CORS
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(bodyParser.json());
app.get('/sightings', (req, res) => {
res.json(sightings);
});
app.post('/sightings', (req, res) => {
req.body.id = (sightings.length + 1).toString();
sightings.push(req.body);
res.json(req.body);
});
app.get('/species', (req, res) => {
res.json(species);
});
const port = process.env.PORT ? process.env.PORT : 8081;
const server = app.listen(port, () => {
console.log("Server listening port %s", port);
});
前端:
export default class Menu extends React.Component {
constructor(props) {
super(props);
this.state = {
key: '',
sightings: [],
}
}
componentDidMount() {
fetch('http://10.0.0.2:3000/sightings')
.then(res => res.json())
.then(res => {
this.setState({sightings: res })
})
.catch((error) => {
console.log(error);
});
console.log(this.state.sightings);
}
顯然,這里的要點是使用數據更新狀態中的瞄准點,但是它不起作用,我只返回了最初分配給this.state.sightings的空對象。
我缺少一些步驟嗎? 我是一個使用節點服務器的初學者,我遵循的各種教程就是這樣做的。
this.setState是一個異步函數,需要一些時間才能完成。 如果要記錄更新的狀態,精確的方法是將其記錄在this.setState的回調中。 這應該工作,
fetch('http://10.0.0.2:3000/sightings')
.then(res => res.json())
.then(res => {
this.setState({sightings: res }, () => {
console.log(this.state.sightings);
})
})
.catch ((error) => {
console.log(error);
});
瀏覽文檔以了解setState的工作原理, https: //reactjs.org/docs/react-component.html#setstate
好的,大家發現一切正常,但是我使用的Android模擬器(Pixel_API_26)卻沒有。 當我切換到Nexus_4_API_23時,一切正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.