useState不重新呈现

时间:2019-09-11 20:11:59

标签: reactjs react-hooks

有人可以帮我弄清楚当我使用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”。但是当我尝试检查它时,上面已经有物品了。

3 个答案:

答案 0 :(得分:1)

// 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 */)

答案 1 :(得分:0)

您的Promise.all通话可能失败,并且此代码与此有关

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

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

尝试创建epmty数组,并将其推入其中

答案 2 :(得分:0)

感谢AngelSalazar,我尝试更改代码

RequestBodyUriSpec