我是 React Native 新手。实际上这是我的第一个应用程序。
我一直在尝试将数据从 Fetch 传递到组件,但没有成功。我上下左右研究了 Google,尝试了数百万种方法,但仍然不行。
这是我的 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 (evaluating 'props.content.first')
我尝试了数百万种方法,但大多数时候这是我看到的错误。如果我执行状态的 console.log,我要么未定义,要么为空。
最佳答案
在您的 Index
中组件,content
prop 最初是未定义的,因为您没有将任何值(通常称为“初始状态”)传递给 useState
在您的 App
中运行组件。
相反,请尝试:
const [ fetchApiData, setApiData ] = useState({
first: {},
second: {}
});
请注意,我已使用 first
填充初始状态和second
项,因为尝试访问树中更下方的元素( image
、 pretitle
等)仍然会抛出错误。
关于javascript - 使用 useState React Native 将获取数据传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60270208/