首页 > 解决方案 > 反应原生按钮点击渲染不同的组件

问题描述

我正在为我的应用程序使用 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;
`

标签: react-nativeexpo

解决方案


在按钮下会有平面列表

你没有使用 FlatList,只显示文本响应,第二个按钮的数据很大,这就是它超级慢的原因。

是我所做的更改,检查这是否是您要查找的内容?

此外,如果您希望一次显示一个数据,您可以使用选项卡或显示/隐藏数据,具体取决于我在代码中所做的选择。


推荐阅读