You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React电商后台:State已存数据库数据但页面无法展示求助

Fixing Your React Customer List Display Issue

Hey there! Let's break down why your customer list isn't showing up on the page—you're almost there, just a couple of small fixes needed.

1. Missing Return Statement in displayCustomerList

The biggest issue is that your displayCustomerList function isn't returning the mapped JSX! You're calling posts.map() but not sending that result back to the render method. Right now, the function returns undefined, so nothing gets rendered to the page.

2. Incorrect Class Name Syntax

You used className="customer.list_display"—the dot here is CSS selector syntax, not how you define classes in React. If you want multiple classes, use a space (like customer list-display) or a single hyphenated name such as customer-list-display.

3. Potential Field Name Mismatch

I noticed you're storing phone in your component state, but trying to render post.phoneNumber in the list. Double-check what your API returns—if the backend sends phone instead of phoneNumber, that field will show up empty.

Modified displayCustomerList Function

Here's the fixed version of your function with all these issues addressed:

displayCustomerList = (posts) => {
  if (!posts.length) return <p>No customers found yet.</p>; // Friendlier fallback than null

  // Add the return keyword to send the mapped JSX back to the render
  return posts.map((post) => (
    // Use post._id as the key instead of index (more stable for dynamic lists)
    <div key={post._id} className="customer-list-display">
      <h3>TEST</h3>
      <h3>{post.name}</h3>
      <p>Customer ID: {post._id}</p>
      <p>Address: {post.address}</p>
      <p>Postcode: {post.postcode}</p>
      // Handle both possible field names to avoid missing data
      <p>Phone: {post.phone || post.phoneNumber}</p>
    </div>
  ));
};

Extra Tip

Using post._id as the key instead of index is better practice—index keys can cause unexpected behavior if you ever sort, add, or remove items from the list later on.

With these changes, your customer list should render properly! Let me know if you run into any other snags.

内容的提问来源于stack exchange,提问作者RossWalker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 10:37:42