【发布时间】:2019-04-18 19:00:18
【问题描述】:
我的 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>
);
}
}
【问题讨论】:
-
我觉得你只需要加
JSON.parse(res.data) -
如果你在axios请求回调中写
console.log(res);,你的数据是什么样的? -
你能分享你的 axios 配置吗?
标签: reactjs