【问题标题】:I cant render and object from state, ReactJS with functional components我无法从状态渲染和对象,ReactJS 与功能组件
【发布时间】:2021-08-11 01:20:30
【问题描述】:

通过这个函数,我可以从 API 中过滤一些对象

const consultarAPI = async () => {
try {
  const consulta = await fetch(URL);
  const respuesta = await consulta.json();
  // Aqui se filtran las noticias
  const noticiasFiltradas = respuesta.filter(
    (noticia) => noticia.categoria === categoria
  );
  setNoticias(noticiasFiltradas);
  setDestacada(noticiasFiltradas[noticiasFiltradas.lenght-1])
  
} catch (error) {
  console.log(error);
}

};

我不知道怎么了。状态“noticias”接收对象数组,“destacada”接收数组的最后一个对象。

在应用程序上,我的组件状态完全符合我的预期。但是,如果我这样做

<h4>{destacada.titulo}</h4>

因为我需要呈现该特定对象的标题。应用程序崩溃,我收到此错误。 TypeError:无法读取未定义的属性“titulo”

它是如何未定义的?在我尝试渲染对象之前,它完美地工作了几秒钟。请我需要帮助。 这些是我的状态:

const [destacada, setDestacada]=useState({});


const [noticias, setNoticias] = useState([]);



const [categoria, setCategoria] = useState("");

【问题讨论】:

  • 检查 noticiasFiltradas[noticiasFiltradas.lenght-1] 返回您期望的值

标签: javascript reactjs state react-functional-component json-server


【解决方案1】:

这里有错别字

setDestacada(noticiasFiltradas[noticiasFiltradas.lenght-1])

这就是 destacada 未定义的原因。

所以把noticiasFiltradas.lenght-1改成noticiasFiltradas.length-1

【讨论】:

  • 对不起!我在写问题时打错了。我的代码输入正确。
【解决方案2】:

我已经解决了这个问题。不要写&lt;h4&gt;{destacada.titulo}&lt;/h4&gt;,而是写&lt;h4&gt;{destacada &amp;&amp; destacada.titulo}&lt;/h4&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-24
    • 2019-03-24
    • 2020-06-04
    • 2021-02-16
    • 2019-02-07
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多