简体   繁体   English

出现反应状态,但仅第一个阵列可访问

[英]React State Appears but Only first array is accessible

I need to loop through an array that is nested within an array in my React State. 我需要遍历嵌套在我的React State数组中的数组。 I see the state is populated with both arrays in Dev Tools, also, when I loop through the parent array with Object.keys(this.state.products).map I get all of the values. 我在开发工具中看到两个数组都填充了状态,当我使用Object.keys(this.state.products).map遍历父数组时,我得到了所有值。 The issue is when I try to loop over the child array, or pull any value from the child array, such as this.state.products[0][3] I get Undefined errors. 问题是,当我尝试遍历子数组或从子数组中提取任何值时,例如this.state.products [0] [3],我得到未定义的错误。

Whats more, is when I console.log this.state.products[0][3] in ComponenetDidUpdate I get the value, so it's like React is setting the state but not all the way? 更重要的是,当我在ComponenetDidUpdate中console.log this.state.products [0] [3]时,我得到了值,这就像React在设置状态但不是一直在进行?

 const { Component } = React; class App extends Component { state = { products: [] }; componentDidMount() { this.apiSearch(); } apiSearch = () => { // api call is made here const API = `http://localhost:5000/products`; fetch(API) // api response log // .then(response => console.log(response)) .then(response => response.json()) .then(data => { this.setState({ products: data }, () => this.setState({ products: data }) ); }) .catch(err => { console.log(err); }); }; render() { return ( <div className="App"> {<div>{typeof this.state.products[0]}</div>} {/* issue is here !!!! */} {<div>{typeof this.state.products[0][3]}</div>} {/* issue is here !!!! */} {this.state.products.forEach(function(element) { console.log(element); })} <br></br> Listings: {Object.keys(this.state.products).map((keyName, i) => ( <li className="listingItem_Parent" key={i}> <span className="listingItem"> {i} Name: {this.state.products[keyName]} </span> </li> ))} <br></br> </div> ); } } ReactDOM.render(<App/>, document.getElementById("root")); 
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> 

I need to iterate through the child array in "products" which is set in state and generate a nice list of them like with map in the first array. 我需要遍历处于状态的“产品”中的子数组,并像第一个数组中的map一样生成一个漂亮的列表。

Your component's render is called before the fetch occurs. fetch发生之前,将调用组件的render At that point, your state just contains { products: [] } , so naturally this.state.products[0][3] fails because this.state.products[0] is undefined at that point. 那时,您的状态仅包含{ products: [] } ,所以自然地this.state.products[0][3]失败了,因为在该点未定义this.state.products[0] You need to either initialize your state such that this.state.products[0][3] is meaningful, or update render so that it doesn't fail when there is nothing in this.state.products . 您需要初始化状态以使this.state.products[0][3]有意义,或者更新render以便当this.state.products没有内容时它不会失败。

There are a fair number of possibilities. 有很多可能性。 First, check the console output, it is likely you're getting a warning explaining what's going on. 首先,检查控制台输出,很可能会收到警告,说明正在发生的情况。

First, check that the state is really an array and not an error or some other object. 首先,检查状态是否确实是数组,而不是错误或其他对象。

Secondly, you are explicitly checking something out of bounds in the initial state (the other answer just posted suggested this). 其次,您正在显式检查初始状态下的某些事物(刚刚发布的其他答案表明了这一点)。

Third, make sure you use an key/ID when iterating over the list, it might not work without it (it should generate a warning). 第三,确保在遍历列表时使用密钥/ ID,如果没有密钥/ ID,它可能无法工作(它会生成警告)。

//something like this
{ this.state.products.map( p => {
    return (<span key={p.id}>{p.name /*whatever*/}</span>) 
} )

Basically make sure that render method works with any and all data, right now there are no checks in place to validate the source so you might have something unexpected crashing your application. 基本上,请确保render方法适用于所有数据,现在没有适当的检查来验证源,因此您可能会意外地使应用程序崩溃。 The hard coded index out of bounds is highly suspect. 硬编码索引超出范围是高度可疑的。

componentDidMount() runs after the first render. componentDidMount()在第一个渲染之后运行。 So, the fetch is not even done by the time the first return is executed, which means this.state.products is still an empty array. 因此,在执行首次返回时甚至没有完成获取操作,这意味着this.state.products仍然是一个空数组。 And you are performing actions on an empty array at this moment. 此时,您正在对空数组执行操作。 Which is why this.state.products[0][3] will fail. 这就是为什么this.state.products[0][3]将失败的原因。

At this moment: 此刻:

this.state.products =[]
this.state.products[0] = undefined
this.state.products[0][3] -> error since you are checking for [3] of undefined. 

You need to check if the array is empty and then perform actions based only when it's not. 您需要检查数组是否为空,然后仅在数组不为空时执行操作。

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

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