![](/img/trans.png)
[英]Getting this error while doing react-redux project. Error:- TypeError: Cannot read property 'map' of undefined in React-Redux project
[英]I'm getting this error “TypeError: Cannot read property 'map' of undefined” on my React project
我是 React 的新手。 我有一個 node.js API。 我正在嘗試創建一個登錄頁面。 我向 API 提出請求,我可以得到回復。 我將返回的答案放入名為“user”的 state 中。 我想用 map function 將其打印到標簽上並檢查數據。 但是,我收到錯誤“TypeError:無法讀取未定義的屬性 'map'。” 我已經用 [] 定義了 state,但我不知道還能做什么。
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
到 function getLogIn 並刪除此行。then(response => console.log(response))
刪除文件中提供的代碼
.then(response => console.log(response))
你不確定你正在迭代一個數組。 一切都在發生,因為在 promise 中鏈接。 a then
返回的內容被轉換為下一個then
的輸入。 因此, console.log
沒有返回任何內容,因此接下來的內容是undefined
。 通過刪除日志或再次返回響應解決了該問題后,您需要確保將響應中所需的部分保存到 state 中。
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 以使其反應到您的模板中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.