我是 React 新手。我有一个 node.js API。我正在尝试创建一个登录页面。我向 API 发出请求,我可以得到响应。我将返回的答案放入名为“user”的状态。我想用 map 函数把它打印到一个标签上并检查数据。但是,我收到错误“类型错误:无法读取未定义的属性‘地图’。”我已经用 [] 定义了状态,但我不知道还能做什么。
import React, { Component } from 'react'
export default class App extends Component {
state = { user: [] }
componentDidMount(){
this.getLogin();
}
getLogin = () =>{
let data = {
"email": "xxxxxx@gmail.com",
"password": "123456"
}
fetch("http://localhost:5000/api/auth/login",{
method:'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(response => console.log(response))
.then(data => this.setState({ user : data }));
}
render() {
return (
<div>
{this.state.user.map(data => (
<h3> {data.data.access_token} </h3>
))}
</div>
)
}
}
{
我在这里添加了从 API 返回的答案。
success: true, access_token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVmY…I5M30.9r9iRA0lyXTy-MjUr2QN9RrxGneqyUoVZM8eFeXoK1s", data: {…}}
access_token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVmYzNmYmFiNjFhOWQzMGQwNDNjY2I0OSIsIm5hbWUiOiJOZW1yYW4gQWtzYWthbCIsImlhdCI6MTYwOTc5MDI5M30.9r9iRA0lyXTy-MjUr2QN9RrxGneqyUoVZM8eFeXoK1s"
data: {name: "Red Reddington", email: "example@gmail.com"}
success: true
__proto__: Object
答案 0 :(得分:1)
必须使用 getLogIn 函数并删除这一行 .then(response => console.log(response))
答案 1 :(得分:0)
删除文件中提供的代码
.then(response => console.log(response))
答案 2 :(得分:0)
您没有确保正在迭代数组。一切都在发生,因为链接然后在承诺中。 then
返回的内容被转换为下一个 then
的输入。因此,console.log
没有返回任何内容,因此接下来会得到 undefined
。通过删除日志或再次返回响应解决了该问题后,您需要确保将响应中所需的部分保存到状态中。
state = { user: [], access_token: '' }
fetch("http://localhost:5000/api/auth/login",{
method:'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then((response) => response.json())
.then((response) => { console.log(response); return response; })
.then((response) => this.setState({
user : response.data,
access_token: response.access_token
}));
注意:确保您存储 access_token 以使其反应到您的模板中。