从API过滤空值

编程入门 行业动态 更新时间:2024-10-08 18:34:52

从<a href=https://www.elefans.com/category/jswz/34/1771441.html style=API过滤空值"/>

从API过滤空值

我使用nodejs构建了后端服务器API并将其链接到我拥有的现有数据库(该数据库充满了空值),然后将后端服务器链接到我的前端react native项目以在屏幕上显示数据所以我试图过滤掉空值,以便我的应用仅显示具有值的值(标题分别是img和摘录),如您在下面的屏幕中看到的那样,我只能得到一个或另一个,有时什么也没有。所以我有一种方法可以使用axios或使用某种过滤功能

这是我在钩子中使用的代码:useArticle.js

import { useEffect, useState } from "react";
import articles from "../api/articles";
import axios from "axios";
export default () => {
  const [docs, setDocs] = useState([]);
  const [errorMessage, setErrorMessage] = useState("");
  const loadApi = async () => {
    // wait for a reponse to get back once it does with some data we asign that data to the reponse variable
    try {
      const response = await axios.get("http://192.168.1.2:3001/articles");
      //console.log(response.data);
      setDocs(response.data.data);
    } catch (err) {
      setErrorMessage("Something went wrong");
    }
  };
  // bad code
  //searchApi("pasta");
  useEffect(() => {
    loadApi();
  }, []);

  return [loadApi, docs, errorMessage];
};

这是我在TrackCreateScreen.js上使用的代码

import React, { useState } from "react";
import { View, Text, StyleSheet, ScrollView, FlatList } from "react-native";
import SearchBar from "../components/SearchBar";
import useResults from "../hooks/useResults";
import ResutlsList from "../components/ResultsList";
import ResutlsListVer from "../components/ResultsListVer";
import useArticles from "../hooks/useArticles";
const TrackCreateScreen = () => {
  const [loadApi, docs, errorMessage] = useArticles();
  /*
  const filterNull = (docs) => {
    return docs.filter((doc) => {
      if ((doc.title = ".")) return doc.title;
    });
  };
  console.log(filterNull(docs)); */

  return (
    <View>
      <FlatList
        data={docs}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => (
          <View style={{ backgroundColor: "#abc123", padding: 10, margin: 10 }}>
            <Text style={{ color: "#fff", fontWeight: "bold" }}>
              {item.title}
            </Text>
            <Text style={{ color: "#fff" }}>{item.excerpt}</Text>
          </View>
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    //flex: 1, // when ever we have a content that is being cut off or expanding off the screen
  },
  Text: {
    fontSize: 32,
    alignItems: "center",
  },
});
export default TrackCreateScreen;

回答如下:

假设您使用Express框架,以下是一些快速代码供您使用:

更多推荐

从API过滤空值

本文发布于:2024-05-07 12:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756309.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!