.map 函数不适用于 React Native

.map function not working with React Native

我有一个 .map() 函数,里面有 JSX 代码。虽然,JSX 没有渲染。它仅在我保存文件后呈现。我正在使用 expo (React Native)。

这是我的代码:

import React, { useEffect, useState } from "react";
import * as SecureStore from "expo-secure-store";
import { View, Text, ActivityIndicator } from "react-native";
import { Button } from "react-native-elements";

const Receipts = ({ navigation }) => {
  const [receipts, setReceipts] = useState([]);
  const [loading, setLoding] = useState(true);
  const [result, setResult] = useState({});
  const [keys, setKeys] = useState([]);
  useEffect(() => {
    const getReceiptsData = async () => {
      let token = await SecureStore.getItemAsync("token");
      console.log(token);
      fetch("https://notrealapi/api/receipts", {
        method: "GET",
        headers: {
          Authorization: `JWT ${JSON.parse(token)}`,
        },
      })
        .then((res) => res.json())
        .then((json) => {
          setReceipts(json);
          setLoding(false);
        })
        .catch((error) => console.error(error));
    };

    getReceiptsData();
    processReceipts();
  }, []);

  const processReceipts = () => {
    const dubps = [];
    const resultObj = {};
    receipts.map((item) => {
      if (dubps.includes(item.merchant_name)) {
        resultObj[item.merchant_name] =
          resultObj[item.merchant_name] + parseFloat(item.total);
      } else {
        resultObj[item.merchant_name] = parseFloat(item.total);
        dubps.push(item.merchant_name);
      }
    });
    setResult(resultObj);
    setKeys(Object.keys(resultObj));
  };

  const exportReport = async () => {
    let token = await SecureStore.getItemAsync("token");
    fetch("https://notrealapi/api/export", {
      method: "GET",
      headers: {
        Authorization: `JWT ${JSON.parse(token)}`,
      },
    })
      .then((res) => res.json())
      .then((json) => {
        console.log(json);
      })
      .catch((error) => console.error(error));
  };

  const renderSummary = () => {
    return keys.map((key) => {
      return (
        <View>
          <Text
            key={key}
            style={{
              fontSize: 15,
              fontWeight: "normal",
              paddingBottom: 50,
            }}
          >
            {`You have spent $${result[key].toString()} at ${key}`}
          </Text>
        </View>
      );
    });
  };

  return (
    <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
      {loading ? (
        <ActivityIndicator size="large" color="blue" />
      ) : (
        <>
          <Text style={{ fontSize: 30, fontWeight: "bold", paddingBottom: 50 }}>
            Summary:
          </Text>
          {renderSummary()}
          <Button
            type="outline"
            title="Export detailed report"
            onPress={exportReport}
          />
          <Text style={{ fontSize: 10, marginTop: 10 }}>
            *The detailed report shall be sent by email.
          </Text>
        </>
      )}
    </View>
  );
};

export default Receipts;

注意:它确实有效,但仅当我保存文件并使用 expo CLI 刷新时。此外,renderSummary() 函数发生错误。

更新:keys 可以等于 ["Costco"] 并且 result 可以等于 {Costco: 69.99}

getReceiptsData() 中的提取解决之前,您是 运行 processReceipts()

注意此示例中控制台日志的顺序。

import React, { useEffect, useState } from "react";

const Receipts = () => {
  const [receipts, setReceipts] = useState([]);
  const [loading, setLoding] = useState(true);
  const [result, setResult] = useState({});
  const [keys, setKeys] = useState([]);

  useEffect(() => {
    const getReceiptsData = async () => {
      fetch("https://rickandmortyapi.com/api/character/1", {
        method: "GET"
      })
        .then((res) => res.json())
        .then((json) => {
          console.log("getReceiptsData resolves");
          setReceipts(json);
          setLoding(false);
        })
        .catch((error) => console.error(error));
    };

    getReceiptsData(); // js won't wait here
    processReceipts();
  }, []);

  const processReceipts = (json) => {
    console.log("processReceipts()");
  };
  return null;
};

export default Receipts;


相反,在获取解析时处理数据操作。

import React, { useEffect, useState } from "react";

const Receipts = () => {
  const [loading, setLoding] = useState(true);
  const [result, setResult] = useState({});

  useEffect(() => {
    const getReceiptsData = async () => {
      fetch("https://rickandmortyapi.com/api/character/1", {
        method: "GET"
      })
        .then((res) => res.json())
        .then((json) => {
          console.log("getReceiptsData resolves");
          processReceipts(json);
          setLoding(false);
        })
        .catch((error) => console.error(error));
    };

    getReceiptsData();
  }, []);

  const processReceipts = (json) => {
    console.log("processReceipts()");
    // do some work and then setResult
  };
  return null;
};

export default Receipts;


此外,尽可能避免存储从另一个状态派生的状态。您应该将服务器有效负载转换为可用数据:

  • 当您收到有效载荷时,然后将其设置为状态 OR
  • 渲染时