我試圖在 REACT 中使用 .map() 呼叫異步函式來填充表資料單元格。異步函式正在使用正在迭代的陣列中的資料呼叫我的應用程式的后端。
被呼叫的函式在正確呼叫時回傳一個數字。這是我第一次發布問題,所以任何幫助都很棒!如果我需要添加更多資訊,我會的。
謝謝你。
{tableInfo.map(info => (
<tr>
<td key={info.name}>{info.name}</td>
<td key={info.price}>{info.price}</td>
<td key={info.amount}>{info.amount}</td>
<td>
{async () => await fetchCurrentPrice.getPrice(info.name)}
</td>
</tr> ))}
uj5u.com熱心網友回復:
async函式總是回傳承諾。您無法在渲染期間異步獲取資料。
你需要一個useEffect鉤子來運行收集資料的函式,然后一個useState鉤子來存盤它,以及在你等待它時顯示加載狀態的邏輯。
const MyRow = ({ info }) => {
const [currentPrice, setCurrentPrice] = useState(null);
useEffect(() => {
fetchCurrentPrice.getPrice(info.name).then(setCurrentPrice);
}, [info]);
return <tr>
<td key={info.name}>{info.name}</td>
<td key={info.price}>{info.price}</td>
<td key={info.amount}>{info.amount}</td>
<td>{currentPrice ?? <Loading />}</td>
</tr>
}
和
{tableInfo.map(info => <MyRow key={info.name} info={info} />)}
uj5u.com熱心網友回復:
為 tr 標簽使用單獨的組件并在其中呼叫它。
const Component = (props) => {
const {info} = props
useEffect(() => {
// call your api and set it to state
}, [])
return <tr>
<td key={info.name}>{info.name}</td>
<td key={info.price}>{info.price}</td>
<td key={info.amount}>{info.amount}</td>
<td>
{async () => await fetchCurrentPrice.getPrice(info.name)}
</td>
</tr>
}
{tableInfo.map(info => <Component info={info} />)}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/369626.html
標籤:javascript 节点.js 反应 承诺 数组.prototype.map
上一篇:將反應路由器轉換為v6
下一篇:如何在反應組件中覆寫背景影像?
