【发布时间】:2020-01-10 02:33:11
【问题描述】:
我需要遍历一个嵌套在我的 React State 中的数组中的数组。我看到状态是用开发工具中的两个数组填充的,此外,当我使用 Object.keys(this.state.products).map 遍历父数组时,我得到了所有值。问题是当我尝试遍历子数组或从子数组中提取任何值时,例如 this.state.products[0][3] 我得到未定义的错误。
更重要的是,当我在 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>
我需要遍历设置为 state 的“products”中的子数组,并生成一个很好的列表,就像第一个数组中的 map 一样。
【问题讨论】:
-
感谢您提供 minimal reproducible example 来演示问题。我已让您的 Stack Snippet 可运行。下次你可以这样做:meta.stackoverflow.com/questions/338537
-
虽然我刚刚注意到
fetch,但您需要将其替换为占位符才能使其真正可运行。 -
抱歉,我的后端基本上是用两个数组填充状态:{ "products": [ [ 1, 1, "2019-09-06", "Tackle Amazon Machine Image", "ami" , 1000 ], [ 2, 1, "2019-09-06", "Tackle for GovCloud", "saas", 5000 ] }
标签: javascript arrays reactjs state