reactjs - 如何在 react-native 功能组件中将获取数据设置为文本字段
问题描述
我正在学习 react-native 并且有一个关于获取数据并将它们传递给文本组件的问题。我从我的 node.js 后端获取了我的数据,但不知道如何将这些数据传递给组件。以下是我到目前为止尝试过的代码。
const TableView = () => {
const [details, setDetails] = useState('');
const getUserData = async () => {
fetch('https://----.herokuapp.com/getIncomePerUser', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: data,
month: value,
}),
})
.then(response => response.json())
.then(response => {
console.log('Test');
console.log(response);
const array = response;
for (const i of array) {
const total = i.total;
setDetails(total);
console.log(total);
}
})
.catch(err => {
console.log(err);
});
});
};
useEffect(() => {
getUserData();
}, []);
return (
<Text Value={details}></Text> //I need to set my fetch data this text component
)
}
解决方案
如果您有一个值数组并且想要显示它们,您可以使用:
const TableView = () => {
const [details, setDetails] = useState('');
const getUserData = async () => {
fetch('https://----.herokuapp.com/getIncomePerUser', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: data,
month: value,
}),
})
.then(response => response.json())
.then(response => {
setDetails(response.map(r => r.total));
})
.catch(err => {
console.log(err);
});
});
};
useEffect(() => {
getUserData();
}, []);
return (<>
{details.map((d, i) => <Text key={i}>{d}</Text>)}
</>)
}
如果您只有一个值,只需将您的文本组件替换为:
<Text>{details}</Text>
推荐阅读
- flutter - Flutter 最佳架构模式
- javascript - Firebase 扩展:使用 Stripe 运行订阅付款不返回 sessionId
- aws-lambda - 如何找出为 AWS Lambda 预安装的受信任 CA?
- json - SwifUI:我下载的 JSON 是否保存到 coreData?
- sql - 具有不同数据类型 SQL 的内连接
- domain-driven-design - 当模型与配置表之类的聚合根无关时,我将模型放在哪里
- r - 如何在多小提琴图中为每把小提琴添加中点?
- node.js - 开玩笑检查设置是真还是假
- javascript - 如何将int粘贴到require中?
- node.js - 安装包 quick.db 失败