[英]Mapping through state: (TypeError): this.state.[something].map is not a function
我正在嘗試通過我的 state 進行 map,我從外部 API 收集了數據。
但是,當我這樣做時,我在這里收到此錯誤: TypeError: this.state.stocks.map is not a function
我想通過 function 將結果呈現到前端,以便該站點對 state.favorites 是動態的。 通過 console.log(),我可以看到數據存儲在 state 中。
我發現其他人有類似的問題,但答案沒有解決。
更新:我已經更改了 componentDidMount(),它現在生成了一個數組。 問題是我沒有從 renderTableData() 函數中得到任何渲染。
console.log 顯示了這個數組:
0: {symbol: "ARVL", companyName: "Arrival", primaryExchange: "AESMSBCDA)LNKOS/ TLTE(N GAEQLGAR ", calculationPrice: "tops", open: 0, …}
1: {symbol: "TSLA", companyName: "Tesla Inc", primaryExchange: " RNK EAASGTDACLN)LE/OGMELAQSTB (S", calculationPrice: "tops", open: 0, …}
2: {symbol: "AAPL", companyName: "Apple Inc", primaryExchange: "AMTGS/C) AALGDRSTNLEOEL(S BAE NQK", calculationPrice: "tops", open: 0, …}
length: 3
__proto__: Array(0)
這是我的代碼:
import React, { Component } from 'react'
import './Table.css';
class Table extends Component {
constructor (props) {
super(props);
this.state = {
favorites: ['aapl', 'arvl', 'tsla'],
stocks: []
};
}
componentDidMount() {
this.state.favorites.map((favorites, index) => {
fetch(`API`)
.then((response) => response.json())
.then(stockList => {
const stocksState = this.state.stocks;
const stockListValObj = stockList;
console.log(stocksState)
console.log(stockListValObj)
this.setState({
stocks: [
... stocksState.concat(stockListValObj)
]
}, () => { console.log(this.state.stocks);});
})
})
}
renderTableData() {
this.state.stocks.map((stocks, index) => {
const { companyName, symbol, latestPrice, changePercent, marketCap } = stocks //destructuring
return (
<div key={symbol} className='headers'>
<div className='first-value'>
<h4>{companyName}</h4>
<h4 className='symbol'>{symbol}</h4>
</div>
<div className='align-right'>
<h4>{latestPrice}</h4>
</div>
<div className='align-right'>
<h4 className='changePercent'>{changePercent}</h4>
</div>
<div className='align-right'>
<h4>{marketCap}</h4>
</div>
</div>
);
})
}
render() {
return (
<div className='table'>
<h1 id='title'>Companies</h1>
<div className='headers'>
<h4 className='align-right'></h4>
<h4 className='align-right'>Price</h4>
<h4 className='align-right'>+/-</h4>
<h4 className='align-right'>Market Cap</h4>
</div>
<div>
{this.renderTableData()}
</div>
</div>
)
}
}
export default Table;
我會說這是因為在第一次渲染時,map 會查看 state.stock 並且它是一個空數組。 在第一次渲染之后,調用 componentDidMount 方法來獲取數據。
我建議將 map 包裝成一個條件。 如果庫存沒有任何 object,則返回您想要的任何內容(例如 null 或加載器/微調器)。
像這樣添加它就足以在數組為空的情況下不返回任何內容(它將在第一次渲染后填充,但這對於在獲取失敗時返回錯誤消息也很有用):
this.state.stocks.length > 0 && this.state.stocks.map((stocks, index) => {
您應該始終致力於進行單個 state 更新,嘗試將 state 更新減少為單個更新。
我建議2個解決方案:
async dataFetch() {
const sampleData = this.state.stocks || [];
await this.state.favorites.forEach((favorites, index) => {
fetch(`API`)
.then((response) => response.json())
.then((stockList) => {
sampleData.push(stockList);
// const stocksState = this.state.stocks;
// const stockListValObj = stockList;
// console.log(stocksState);
// console.log(stockListValObj);
// this.setState({
// stocks: [
// ... stocksState.concat(stockListValObj)
// ]
// }, () => { console.log(this.state.stocks);});
});
});
return Promise.resolve(sampleData);
}
componentDidMount() {
this.dataFetch().then((stockValues) => {
this.setState({ stocks: stockValues });
});
}
Promise.all()
這將返回單個數組值,這將更容易更新到庫存 state。 建議:當不從數組返回任何值時,嘗試使用Array.forEach
而不是Array.map
renderTableData
中缺少返回關鍵字
renderTableData() {
this.state.stocks.map((stocks, index) => { ...});
至
renderTableData() {
return this.state.stocks.map((stocks, index) => { ...});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.