我是 React Native 的新手。实际上这是我的第一个应用程序。
我一直在尝试将数据从 Fetch 传递到组件,但没有运气。我已经上下左右研究了谷歌,尝试了数百万种东西,但仍然没有成功。
这是我的 App.js
import React, {useState, useEffect} from 'react';
import { View, StyleSheet, ScrollView } from 'react-native';
import Header from './parts/header';
// import BigNews from './parts/big-news';
import Index from './screens/index.js';
const authorization = { authorization: '1234aa' };
export default function App() {
const [fetchApiData, setApiData] = useState();
useEffect(() =>
fetch('https://example.com/get-app-home.php', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(authorization),
})
.then(res => res.json())
.then(res => {
this.setState({ setApiData: res })
})
.catch(() => this.setState({ hasErrors: true }))
);
return (
<View style={styles.viewport}>
<Header />
<ScrollView style={styles.contentHolder}>
<Index content={fetchApiData}/>
</ScrollView>
</View>
);
}
这是我的 index.js 文件
import React from 'react';
import { View, Text } from 'react-native';
import BigNews from '../parts/big-news';
import SmallNews from '../parts/small-news';
import Colors from '../constants/colors'
const Index = props => {
return (
<View>
<BigNews
image={props.content.first.image}
pretitle={props.content.first.pretitle}
title={props.content.first.title}
introduction={props.content.first.introduction}
style={{color: props.content.first.mark}}/>
<SmallNews
image={props.content.second.image}
pretitle={props.content.second.pretitle}
title={props.content.second.title}
style={{color: props.content.first.mark}}/>
<SmallNews
image={props.content.second.image}
pretitle={props.content.second.pretitle}
title={props.content.second.title}
style={{color: props.content.first.mark}}/>
<SmallNews
image={props.content.second.image}
pretitle={props.content.second.pretitle}
title={props.content.second.title}
style={{color: props.content.first.mark}}/>
</View>
);
}
export default Index;
我经常收到 TypeError: undefined is not an object (evalating 'props.content.first')
我尝试了数百万种方法,但大多数时候这是我看到的错误。如果我执行 console.log of state 我得到未定义或空的。