无法从 Firebase 读取未定义数据的属性'reduce'



我试图git的totalBalance,但我面临错误不能读取属性'reduce'的未定义,同时我可以迭代组件的客户端代码如下

//redux and firebase
import { useSelector} from 'react-redux'
import { useFirestoreConnect, isLoaded, isEmpty} from 'react-redux-firebase'
const Clients = () => {
useFirestoreConnect(["client"]) //the name of collection  on firebase
const clients = useSelector((state) => state.firestore.ordered.client);
const totalBalance = clients.reduce((acc,client)=>(acc + client.balance),0)
console.log(totalBalance);
return (
<div className="client">
<div className="row client_head ">
<div className="col">
<FaUsers />
<span className="ml-2">Clients</span>
</div>
<div className="col text-right">
<span className="d-b">Total:  </span>
<span className="ml-auto ">
{clients.length===0?0:clients.reduce((acc,client)=>(acc + Number(client.balance),0))}
</span>
</div>
</div>
<div className="client_info row text-center">
<table className="mt-3 w-100 table-bordered">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>balance</th>
<th>Details</th>
</tr>
</thead>
<tbody>
{clients.map(client => 
<tr key={client.id}>
<td className="p-3">3</td>
<td>{client.firstName}</td>
<td>{client.lastName}</td>
<td>{client.email}</td>
<td>{client.balance}</td>
</tr>
)}
</tbody>
</table>
)}
</div>
</div>
);
};
export default Clients

我认为问题是客户端是未定义的,但我不知道原因

这个错误告诉您从redux中选择的clients对象是undefined。它可能是作为undefined开始,然后异步地填充数据,所以在第一次渲染时它将是undefined,但之后很好。如果它继续保持undefined,那么在你的代码的其他地方有问题。

有两种简单的方法来处理可能还不存在的数据。

  1. 您可以将undefined替换为空数组,并正常渲染组件的其余部分。你会有一个没有项目和0余额的列表。
const clients = useSelector((state) => state.firestore.ordered.client) || [];
  1. 你可以停止渲染组件的其余部分。要么不渲染,要么渲染一些加载屏幕。
const clients = useSelector((state) => state.firestore.ordered.client);
if ( ! clients ) {
return (<div>Loading...</div>);
}
// the rest of the component continues below

最新更新