我的React应用程序中出现以下错误:
users.map不是函数
I have tried many solutions posted on Stack Overflow,但似乎无法解决我的问题。
我使用下面的代码提交了文件名,并且工作正常。这是我的问题。每次我点击“提交”按钮时,我 想要连续显示后端的JSON数据(例如,如果我提交3次表单,则需要显示3条JSON数据记录。)
这是JSON的示例:
{"filename":"macofile","message":"success","uid":"20"}
为此,我在 Axios 发布响应
中设置了以下代码行this.setState({
users: res.data,
loading: false,
});
我也尝试过
users: res
或
users.push(res.data);
这是我的代码:
import React, { Component } from "react";
import axios, { post } from "axios";
class FilePage extends React.Component {
constructor(props) {
super(props);
this.state = {
value: "",
filename: "",
loading: false,
users: [],
error: null
};
this.handleChange = this.handleChange.bind(this);
}
_handleSubmit(e) {
e.preventDefault();
//send it as form data
const formData = new FormData();
formData.append("filename", this.state.filename);
//alert(this.state.filename);
this.setState({ loading: true }, () => {
axios
.post("http://localhost/apidb_react/up.php", formData)
.then(res => {
this.setState({
users: res.data,
loading: false
});
})
.catch(err => {
console.log(err.message);
});
});
}
// handle form submission
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
render() {
const { loading, users, error } = this.state;
return (
<div>
<form onSubmit={e => this._handleSubmit(e)}>
<b>filename:</b>
<input
tyle="text"
className="form-control"
value={this.state.filename}
name="filename"
onChange={this.handleChange}
/>
<button
className="submitButton"
type="submit"
onClick={e => this._handleSubmit(e)}
>
submit
</button>
</form>
<React.Fragment>
<h3>Display Data each time record is submitted</h3>
{error ? <p>{error.message}</p> : null}
{!loading ? (
users.map(user => {
const { filename, message, uid } = user;
return (
<div key={uid}>
<p>Userid: {uid}</p>
<p>File Name: {filename}</p>
<p>Message: {message}</p>
<hr />
</div>
);
})
) : (
<h3>Loading...</h3>
)}
</React.Fragment>
</div>
);
}
}
答案 0 :(得分:1)
您的res.data似乎是对象而不是数组-> {"filename":"macofile","message":"success","uid":"20"}
。因此,您将需要通过以下方式遍历对象:
Object.keys(users).map(key => console.log(users[key]))