所以我一直在研究这个React应用。
import React, { PureComponent } from "react";
import axios from "axios";
const serverLocation = require("../config/keys.js").server;
var data = [];
export default class StanjeNaCestah extends React.Component {
state = {
datag: [],
finished: false
};
componentDidMount() {
axios.get(`${serverLocation}/api/content/road-conditions`).then(res => {
this.setState(
{
datag: res.data
},
function() {
console.log("Datag updated");
console.log(this.state);
this.setState(
{
finished: true
},
() => {
console.log("Finished true");
}
);
}
);
for (var key in this.state) {
data.push(this.state[key]);
}
});
}
componentWillUpdate() {
console.log("WillUpdating");
console.log(this.state);
}
render() {
console.log("Render called");
console.log(this.state.datag.items);
//const itemz = this.state.datag.items.map((item, key) => <h3>{item}</h3>);
let numbers;
//numbers = this.state.datag.items;
if (this.state.datag.items) {
numbers = this.state.datag.items.forEach(item => {
console.log("Iterating through for item " + item.title);
return <div>{item.title}</div>;
});
}
console.log("Logging numbers");
console.log(numbers);
return <ul>{numbers}</ul>;
/*return (
<div className="container">
<div className="col-xs-8">
<h1>{this.state.datag.title}</h1>
{itemz}
</div>
</div>
);*/
}
}
问题是渲染中的代码。如您所见,我正在检查this.state.datag.items是否未定义。我在函数第二行中调用的console.log返回有效值。但是后来,我在其中记录数字的地方返回未定义。 forEach中的部分记录有效值... 请把我的想法用光了。帮助。
答案 0 :(得分:1)
您遇到的问题是Array.prototype.forEach
没有返回值。我怀疑,鉴于您编写的代码,您正在寻找Array.prototype.map
。
根据MDN documentation for Array.prototype.forEach
:
返回值
undefined
numbers = this.state.datag.items.map(item => {
console.log("Iterating through for item " + item.title);
return <div>{item.title}</div>;
});