react-native - 反应原生按钮点击渲染不同的组件
问题描述
我正在为我的应用程序使用 Expo React 本机。我创建了三个按钮。当用户单击按钮时,它将获取数据并将其呈现在一个屏幕上。每个按钮将按钮将获取不同的 api。在按钮下会有一个平面列表,它将在其中显示数据。我可以一键单击显示数据,但我不知道如何显示其他按钮 api。我在codesandbox中分享我的代码。ps: Below code make this app get super slow
这是我的代码
import React from 'react';
import { Text, View, ScrollView } from 'react-native';
import styled from 'styled-components';
import PressableButton from './Button';
import axios from 'axios';
const api = "https://jsonplaceholder.typicode.com/users";
const anApi = "https://jsonplaceholder.typicode.com/photos"
const Data = ({ data }) => {
return (
<View style={{ flex: 1 }}>
<Text>{JSON.stringify(data, null, 4)}</Text>
</View>
)
}
const AnData = ({ andata }) => {
return (
<View style={{ flex: 1 }}>
<Text>{JSON.stringify(andata, null, 1)}</Text>
</View>
)
}
export default function App() {
const [data, setData] = React.useState([]);
const [anotherdata, setanotherData] = React.useState([]);
const updateState = async () => {
await axios(api)
.then((res) => {
setData(res.data);
})
.catch((err) => {
console.log("failed to catch", err);
});
};
const anoThereState = async () => {
await axios(anApi)
.then((res) => {
setanotherData(res);
})
.catch((err) => {
console.log("failed to catch", err);
});
};
return (
<React.Fragment>
<Container>
<PressableButton onPress={updateState} title='First button' bgColor='#4267B2' />
<PressableButton onPress={anoThereState} title='Second button' bgColor='lightblue' />
<PressableButton onPress={() => true} title='Third button' bgColor='#4267B2' />
</Container>
<Scroll>
{data && data === undefined ? <Text>loading</Text> : <Data data={data} />}
{anotherdata && anotherdata === undefined ? <Text>loading</Text> : <AnData andata={anotherdata} />}
</Scroll>
</React.Fragment>
);
}
const Container = styled.View`
flex-direction: row;
justify-content: center;
padding: 70px 0px 20px 0px;
`;
const Scroll = styled.ScrollView`
flex: 1;
`
解决方案
在按钮下会有平面列表
你没有使用 FlatList,只显示文本响应,第二个按钮的数据很大,这就是它超级慢的原因。
这是我所做的更改,检查这是否是您要查找的内容?
此外,如果您希望一次显示一个数据,您可以使用选项卡或显示/隐藏数据,具体取决于我在代码中所做的选择。
推荐阅读
- javascript - 在 React 中自动缩放输入到值的宽度
- javascript - 如何在 for 循环 JavaScript 中生成 div 元素 ID
- javascript - 如何修复 Komodo IDE 中逐步调试 javascript 的错误?
- core-data - 无法转换“FetchedResults”类型的值
' 到预期的参数类型 'Set ' - java - 在不允许 getEnv 调用的受保护环境中创建 AmazonHttpClient
- reactjs - VS Code:React 应用的编译时间长
- c++ - 为什么循环这个数组时我的代码不能正常工作
- kubernetes - 如何在命令行上替换 Helm values.yaml 中数组项中的特定属性值而不是整个数组/映射?
- sql - SQL Group by,但如果值相同则允许重复
- dart - 使用 Dart 中的 map() 等内置方法将嵌套列表(二维列表)转换为一个元素列表