【问题标题】:setting state on react native issue在反应本机问题上设置状态
【发布时间】:2020-05-11 22:14:12
【问题描述】:

我正在尝试使用 axios 在我的 react 本机应用程序屏幕上打印从使用 nodejs 构建的后端服务器获得的数据,但由于某种原因我没有得到任何结果

这是我使用的代码:

我的 useArticle 钩子代码:

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://localhost/articles");
      //console.log(response.data);
      setDocs(Array.from(response.data));
    } catch (err) {
      setErrorMessage("Something went wrong");
    }
  };
  // bad code
  //searchApi("pasta");
  useEffect(() => {
    loadApi();
  }, []);

  return [loadApi, docs, errorMessage];
};

// we extracted the resutls logic into this helper function we then imported
// to the main screen in order to use SearchApi , results , errorMessage
// now this helper function can be used inside other components

这里应该显示结果的屏幕:

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();

  /*****************************FUNCTION TO FILTER OUT RESULTS SHOWING USING THE PRICE *************************/

  /*******************************WE WONT NEED THIS UP NOT DOWN************************************* */
  /******************************** REMOVE VIEW AND REPLACE IT WITH <> SO WE DONT HAVE TO WORRY ABOUT ADDING FLEX **********************************************/
  return (
    <View>
      {docs.map((article, index) => (
        <Text key={index}>{article.title}</Text>
      ))}
      <Text style={styles.Text}>{docs.length}</Text>

      <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;

我做了一些控制台。日志,出于某种原因,useState 中的文档只是一个空数组,即使当我使用 console.log (response.data) 时,我的控制台上也显示了所有结果。

我还试图从我的 API 中过滤掉空值,只显示具有实际值的值,所以如果有人能指出我将如何做到这一点,我将不胜感激。

这是我使用 console.log(response.data) 时获得的数据示例:

Object {
  "data": Array [
    Object {
      "_id": "5eb95a068d162448a4e6a9c2",
      "excerpt": "The shooting of Ahmaud Arbery.",
      "img": null,
      "task_id": "92e563d3-82c0-4f13-b393-15d5e570dfad",
      "title": null,
    },
    Object {
      "_id": "5eb95a068d162448a4e6a9c3",
      "excerpt": null,
      "img": null,
      "task_id": "92e563d3-82c0-4f13-b393-15d5e570dfad",
      "title": null,
    },
    Object {
      "_id": "5eb95a068d162448a4e6a9c4",
      "excerpt": null,
      "img": null,
      "task_id": "92e563d3-82c0-4f13-b393-15d5e570dfad",
      "title": null,
    },
    Object {
      "_id": "5eb95a068d162448a4e6a9c5",
      "excerpt": null,
      "img": null,
      "task_id": "92e563d3-82c0-4f13-b393-15d5e570dfad",
      "title": null,
    },

【问题讨论】:

  • 尝试先将 Array.from(response.data) 的返回值保存在一个变量中,然后控制台该变量以交叉检查您是否仍然获得数据;例如 const newValue = Array.from(response.data); console.log(newValue);
  • 当我使用这个 const newValue = Array.from(response.data);控制台.log(newValue);由于某种原因,它也返回了一个空数组
  • 仔细检查 URL 是否正确,您确定这是正确的 URL:http://localhost/articles 吗?把它放在你的浏览器中,看看是否有什么出现
  • 是的,显然 URL 是正确的,否则 console.log(response.data) 不会返回任何结果

标签: javascript node.js reactjs react-native axios


【解决方案1】:

问题可能出在 Array.from 方法中,因为从控制台可以看出您已经获得了数组,因此需要进一步转换它

而不是这个

setDocs(Array.from(response.data));

试试

 setDocs(response.data.data);

【讨论】:

  • 我在使用 Array.form 之前就有过这个,它给了我一个类型错误 undefined is not a function on doc.map 因为 response.docs 的类型是 {} 而不是 []
  • 帮我测试一下@Souhaildq setDocs(response.data.data)
  • 对不起,我的意思是 responose.data 的类型是 {} 而不是 [] 没有 response.docs 我的错,错误是由 docs.map 引起的,因为它需要类型为 [] 的对象,而不是{} 这就是我使用 Array.form @Towerss 的原因
【解决方案2】:

如果您使用过setState 函数,那么setDoc() 可能存在问题,因为设置数据需要时间,因为setStateasync 函数。

【讨论】:

  • 好的,那就试试 setDoc(Array.from(response.data.data),因为你的 response.data 多了一个对象名作为数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-11
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
相关资源
最近更新 更多