繁体   English   中英

useState不重新呈现

[英]useState no rerendering

有人可以帮我弄清楚当我使用ReactHooks改变状态时会怎么回事吗?

   const [newsCatalog, setNewsCatalog] = useState([]);
    useEffect(() => {
     fetchNews();
    });

    const fetchNews = async () => {
      const GetAllNewArticleResults = await GetAllNewArticle();
      let promises = [];
            let tempNewsCatalog = newsCatalog;
            GetAllNewArticleResults.map(async e => {
              promises.push(
                await htmlToJson.parse(
                  e.HTMLNewsCode,
                  {
                    title: function($doc) {
                      return textTruncate($doc.find("H2").text(), 50);
                    },
                    link: function($doc) {
                      return $doc.find("A").attr("href");
                    },
                    content: function($doc) {
                      return textTruncate($doc.find("P").text(), 80);
                    },
                    imageURL: function($doc) {
                      return $doc.find("img").attr("src");
                    }
                  },
                  function(err, result) {
                    tempNewsCatalog.push({
                      ...result
                    });
                  }
                )
              );
              return null;
     });

    Promise.all(promises).then(() => {
      setNewsCatalog(newsCatalog, ...tempNewsCatalog);    
    }); 
};


          return (
            <div className="container mb-4" id="News">
              <div className="h4 mb-3">OUR NEWS</div>
              <div className="d-flex justify-content-between flex-wrap mw-90">
                {newsCatalog.length}
              </div>
            </div>
          );

当我尝试运行它时,它将在“ newsCatalog.length”中显示“ 0”。 但是当我尝试检查它时,上面已经有物品了。

// helper method
function htmlToJson(htmlNewsCode) {
 return new Promise((resolve, reject) => {
   htmlToJson.parse(
     htmlNewsCode,
     {
       title: function($doc) { return textTruncate($doc.find("H2").text(), 50); },
       // implement your other methods
     },
     (err, result) => { 
       if (err) { 
        reject(err);
        return;
       }

       resolve(result)
     }
   )
 })
}


// your component
const [newsCatalog, setNewsCatalog] = React.useState([]);

React.useEffect(() => {

 async function fetchNews() {
  // TODO: Implement error handling using try/catch
  const GetAllNewArticleResults = await GetAllNewArticle();
  const promises = GetAllNewArticleResults.map((e) => {
   return htmlToJson(e. HTMLNewsCode);
  })

  const results = await Promise.all(promises);
  setNewsCatalog(prev => [...prev, ...results]);
 }

 fetchNews();

}, /* You probably need to specify the DEPS */)

您的Promise.all调用可能失败了,并且此代码存在问题

tempNewsCatalog.push({
   ...result
});

它正在推向newsCatalog 因为它是对象,并通过指针与tempNewsCatalog连接。 因此,您有价值观,但没有回报。

尝试创建epmty数组,然后将其推送到此处

感谢AngelSalazar我尝试更改代码

const [newsCatalog, setNewsCatalog] = useState([]);

React.useEffect(() => {
  async function fetchNews() {
          // TODO: Implement error handling using try/catch
    const GetAllNewArticleResults = await GetAllNewArticle();
    let promises = [];

    GetAllNewArticleResults.map(e => {
      promises.push(
        htmlToJson.parse(
                e.HTMLNewsCode,
                {
                  title: function($doc) {
                    return textTruncate($doc.find("H2").text(), 50);
                  },
                  link: function($doc) {
                    return $doc.find("A").attr("href");
                  },
                  content: function($doc) {
                    return textTruncate($doc.find("P").text(), 80);
                  },
                  imageURL: function($doc) {
                    return $doc.find("img").attr("src");
                  }
                },
                function(err, result) {
                  return result;
                }
              )
            );
          });

          const results = await Promise.all(promises);
          setNewsCatalog(prev => [...prev, ...results]);
     }

   fetchNews();
 }, []);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM