【发布时间】:2018-12-23 02:17:31
【问题描述】:
我尝试解决我的问题,但无法处理。 我使用 Express JS 创建了 API,我想显示(映射)我的状态数组。 在 componentDidMount() 我更新 listOfUsers[] 和 console.log 返回正确的数据。当我想在 render() 中映射我的数组时,它会返回一些错误:
Uncaught (in promise) TypeError: this.state.listOfUsers.map is not a 功能
未捕获的类型错误:this.state.listOfUsers.map 不是函数
警告:无法在未安装的设备上调用 setState(或 forceUpdate) 零件。这是一个无操作,但它表明您的内存泄漏 应用。要修复,取消所有订阅和异步任务 在 componentWillUnmount 方法中。
import React, { Component } from 'react';
import axios from 'axios';
class MeetingItem extends Component {
state = {
meetings: [],
listOfUsers: []
}
componentDidMount() {
//get meeting info
axios.get(`http://localhost:3000/meetings/`+ this.props.match.params.id)
.then(res => {
const meetings = res.data;
this.setState({ meetings });
//console.log(res.data);
});
axios.get(`http://localhost:3000/takePart/`)
.then(res => {
for(var i = 0; i < res.data.length; i++){
//for current meeting
if(res.data[i]['meetingId'] == this.props.match.params.id){
//set listOfUsers
axios.get(`http://localhost:3000/users/`+ res.data[i]['userId'])
.then(res => {
const user = res.data;
this.setState({
listOfUsers : user
});
//in that place data is return
console.log(this.state.listOfUsers);
});
}
}
});
}
takePart = () => {
console.log("take");
const takePart = {
meetingId: this.props.match.params.id,
userId: sessionStorage.getItem('userId'),
};
//x-www-form
let formBody = [];
for (let property in takePart) {
let encodedKey = encodeURIComponent(property);
let encodedValue = encodeURIComponent(takePart[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
axios.post(`http://localhost:8000/takePart`, formBody, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
.then(res => {
console.log(res);
console.log(res.data);
//if successfully added a meeting then display alert
if(res.status == "200"){
alert("Thank you. See you later.");
}else{
alert("Sorry we can't handle that. Please repeat for a while.");
}
})
}
render() {
var users = this.state.listOfUsers.map(user => {
return (
<p>{user.firstName}</p>
)
});
return (
<div className="MeetingItem">
<h1>{/*this.props.match.params.id*/}</h1>
<p>Title: {this.state.meetings['title']}</p>
<p>Description: {this.state.meetings['description']}</p>
<p>Author: {this.state.meetings['author']}</p>
<p>lattitude: {this.state.meetings['lattitude']}</p>
<p>longitude: {this.state.meetings['longitude']}</p>
<p>date: {this.state.meetings['date']}</p>
<p>time: {this.state.meetings['time']}</p>
<p>{users}</p>
<div className="btn btn-default" onClick={this.takePart}>Take part</div>
</div>
);
}
}
export default MeetingItem;
有什么建议吗?
【问题讨论】:
-
检查
res.data。我确信它不是一个数组。map是Array的方法之一,所以会报错。
标签: javascript reactjs