我无法从状态渲染和对象,ReactJS 与功能组件
Posted
技术标签:
【中文标题】我无法从状态渲染和对象,ReactJS 与功能组件【英文标题】:I cant render and object from state, ReactJS with functional components 【发布时间】: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] 返回您期望的值 【参考方案1】:这里有错别字
setDestacada(noticiasFiltradas[noticiasFiltradas.lenght-1])
这就是 destacada
未定义的原因。
所以把noticiasFiltradas.lenght-1
改成noticiasFiltradas.length-1
【讨论】:
对不起!我在写问题时打错了。我的代码输入正确。【参考方案2】:我已经解决了这个问题。不要写<h4>destacada.titulo</h4>
,而是写<h4>destacada && destacada.titulo</h4>
【讨论】:
以上是关于我无法从状态渲染和对象,ReactJS 与功能组件的主要内容,如果未能解决你的问题,请参考以下文章
将对象存储在状态时渲染中的ReactJS Fetch Type错误
ReactJS / Javascript - 无法渲染对象中项目的组件