0

以下组件有什么问题?它抛出一个错误,而具有生命周期方法的原始基于类的版本工作正常?

import React, { useState, useEffect } from "react";
import axios from "axios";
const  NewsHook = ()=> {
  const [mount, setMount] = useState(false);
  const [news, setNews] = useState([]);
  useEffect(() => {
    setMount(true);
    axios.get('https://hn.algolia.com/api/v1/search?query=react')
        .then(result => {
                if (mount){
                    setNews({
                        news: result.data.hits,
                    })
                }
            }
        );
    return () => {
      setMount(false);
   }
  }, [mount]);

  return (
        <ul>
            {news.map(topic => (
                <li key={topic.objectID}>{topic.title}</li>
            ))}
        </ul>
  );
}
export default NewsHook
4

3 回答 3

0

您不需要设置挂载状态,因为 useEffect 将在组件挂载时自动工作,如果您希望它只工作,则添加空数组 [] 作为第二个参数

并且您必须将您的 Axios 请求包含在 useEffect 中,以像这样的异步函数:

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

const  NewsHook = ()=> {
  const [news, setNews] = useState([]);

  useEffect(() => {
    const getNews = async () => {
      const result  = await axios.get('https://hn.algolia.com/api/v1/search?query=react');
      setNews({
        news: result.data.hits,
      })
    };
    getNews();
  }, []);

  return (
    <ul>
      {news.map(topic => (
        <li key={topic.objectID}>{topic.title}</li>
       ))}
    </ul>
  );
};

export default NewsHook
于 2020-01-31T11:42:55.840 回答
0

解决方案如下:

setNews(result.data.hits);
于 2020-01-31T11:05:03.037 回答
0

问题是因为数据正在获取。所以新闻仍然是空的。要么使用异步来解决问题,要么以这种方式进行:)

import React, { useEffect, useState } from "react";
import axios from "axios";
import "./styles.css";

export default function App() {
  const [mount, setMount] = useState(false);
  const [news, setNews] = useState([{ new: null }]);

  useEffect(() => {
    setMount(true);
    axios
      .get("https://hn.algolia.com/api/v1/search?query=react")
      .then(result => {
        setNews({ new: result.data.hits });
      });

    return () => {
      setMount(false);
    };
  }, [mount]);

  return (
    <div>
      <ul>
        {news.new == null ? (
          <h2>Loading</h2>
        ) : (
          news.new.map(item => {
            return <li key={item.objectID}>{item.title}</li>;
          })
        )}
      </ul>
    </div>
  );
}

它会解决你的问题。希望对您有所帮助:)

于 2020-01-31T09:09:10.117 回答