首页 > 解决方案 > 如何在 React JSX 中映射包含 JSON 对象的数组?

问题描述

我在我的 redux 操作中从 firebase 存储获取 JSON 对象。我将 JSON 对象存储在关联数组中。当我尝试执行 this.props.expenses 时,我会取回数组。

但我无法在 JSX 中映射数组??

import { SHOW_EXPENSE } from './types';
import database from '../config/firebase';
export const showExpenses = () =>  dispatch => {

const expenses = [];

        database.ref()
        .once('value')
        .then((snapshot) => {


                snapshot.forEach((childSnapshot) => {

                        expenses.push({

                              id: childSnapshot.key,
                              ...childSnapshot.val()        

                        })


                });

        });

        console.log(expenses);

    dispatch({

        type: SHOW_EXPENSE,
        expenses :  expenses     

})

return expenses;

};

这是我的 console.log(expenses);

0: {id: "-LUumVQzeXBN8iK81EVO", expense_amount: "500", expense_name: 
"bike service"}
1: {id: "-LUumeeCeYIdd2G4Pz5K", expense_amount: "1500", 
 expense_name: "tire change"}
 length: 2__proto__: 
 Array(0)

当我尝试映射 this.props.expenses 时,它什么也不返回。

{this.props.expenses.map( data =>

      {data.expense_amount}
      {data.expense_name}
});

标签: javascriptreactjsreduxassociative-array

解决方案


推荐阅读