Javascript 如何从ReactJS setState查找对象数组的长度?
我无法找到/打印由ReactJSJavascript 如何从ReactJS setState查找对象数组的长度?,javascript,reactjs,Javascript,Reactjs,我无法找到/打印由ReactJSsetState设置的对象数组的长度。我的component.js如下 import React from 'react'; class MyComponent extends React.Component { constructor(props) { super(props); this.state = { loading: true, error: false,
setState
设置的对象数组的长度。我的component.js如下
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
error: false,
items: []
};
}
componentDidMount() {
fetch('http://localhost:8000/api/v2/pages/1')
.then(response => response.json())
.then(data => this.setState({ items: data }));
}
render() {
console.log(this.state.items.content.length); // Gives error that says this.state.items is not defined
return (
<React.Fragment>
</React.Fragment>
);
}
}
export default MyComponent;
我试图获得setState
设置的对象内数组“content”的长度
背景故事:
我的目标是通过在render()
因此,当条件为真时,值是只读的,即对象中有值。因为
这个.state.items
开始时是一个空数组(这很奇怪,因为后来它看起来像一个对象),您首先需要确保定义了这个.state.items.content
这样做:
console.log(this.state.items.content && this.state.items.content.length);
或者在你的实际情况中
if(this.state.items.content && this.state.items.content.length > 0){
//access values from this.state.items
}
希望这有助于记住,在第一次渲染中,项目数组为空,道具内容不存在。因此,在正确获取数据后,可能需要检查长度:
componentDidMount() {
fetch('http://localhost:8000/api/v2/pages/1')
.then(response => response.json())
.then(data => this.setState({ items: data , itemsLength: data.content.length}));
}
因此,当您要检查长度时,您必须检查此.state.itemsLength是否与null或初始状态不同。该状态正在初始化为数组,但您正在访问
内容
(即未定义的):
为避免进一步更改,请初始化状态,使其遵循与响应相同的结构。例如:
{
loading: true,
error: false,
items: { content: [] }
};
在第一次渲染期间,items数组为空,因此,当您尝试访问items的属性内容时,它不存在,这就是为什么会出现未定义错误的原因。为了克服这个问题,首先要在计算长度之前检查它是否存在。即
if(this.state.items.content&(this.state.items.content.length>0))
请记住React组件中生命周期函数调用的顺序。在初始装载阶段,在componentDidMount()
之前调用render()
。因此,第一次呈现组件时,items只是一个空数组,items.content是未定义的
然后,您可以编写如下条件:
if (this.state.items.content !== undefined && this.state.items.content.length > 0) {
//access values from this.state.items
}
{
loading: true,
error: false,
items: []
};
{
loading: true,
error: false,
items: { content: [] }
};
if (this.state.items.content !== undefined && this.state.items.content.length > 0) {
//access values from this.state.items
}