【发布时间】:2021-03-29 21:06:45
【问题描述】:
我目前正在学习使用 express 和 node 的 crud react。 我在将数据插入数据库方面取得了成功,但是当我想表示使用 .map 时出现错误的数据时,我感到困惑,您可以在下面的
这是我的代码。请帮忙。
import './App.css';
import React, { useState } from 'react';
import axios from 'axios';
function App() {
const [Name, setName] = useState ("");
const [Subject, setSubject] = useState ("");
const [Message, setMessage] = useState ("");
const [Information, setInformation] = useState ("");
const addCRUD = () => {
axios.post('http://localhost:3001/create',{
Name: Name,
Subject: Subject,
Message: Message}).then(() => {
console.log("Success")
})
}
const getCRUD = () => {
axios.get('http://localhost:3001/DATA').then((response) => {
setInformation(response.data)
})
}
return (
<div className="App">
<div className="container">
<form>
<div className="input-group">
<span className="input-group-addon"><i className="glyphicon glyphicon-user"></i></span>
<input onChange={(event)=> {
setName(event.target.value);
}} id="Name" type="text" className="form-control" name="Name" placeholder="Name"/>
</div>
<div className="input-group">
<span className="input-group-addon"><i className="glyphicon glyphicon-comment"></i></span>
<input onChange={(event)=> {
setSubject(event.target.value);
}}id="Subject" type="subject" className="form-control" name="subject" placeholder="Subject"/>
</div>
<div className="input-group">
<span className="input-group-addon">Message</span>
<input onChange={(event)=> {
setMessage(event.target.value);
}}id="Message" type="text" className="form-control" name="Message" placeholder="Message"/>
</div>
</form>
<div className="input-group">
<input onClick={addCRUD}
id="btn" type="button" className="btn btn-warning" name="btn" placeholder="Submit" value="Submit"/>
</div>
</div>
<div className="input-group">
<input onClick={getCRUD}
id="btn" type="button" className="btn btn-primary" name="btn" placeholder="Show Data" value="show data"/>
{Information.map((val,key) => {
return (
<div>
<h3>
Name: {val.Name}
</h3>
</div>
)
}
)}
</div>
</div>
);
}
export default App;
我得到的错误 62 |
63 | 65 | {Information.map((val,key) => { 66 |返回 ( TypeError: Information.map 不是函数
我遇到的错误
【问题讨论】:
-
你必须检查信息是否是一个有效的数组!在您的情况下,您很可能为此未定义。最好的方法是
Array.isArray(Information) && Information.map(() => { //... }); -
嗨!!!谢谢它的工作!现在我明白 .map 是用于数组的,所以变量值需要是数组 []..
标签: javascript reactjs