React Datatable报React child错误 如何渲染嵌套Listing的title
报错原因
你遇到的报错和字段不显示问题来自三个核心问题:
- columns配置存在语法错误:第二列配置错用
id声明字段(该组件通过key属性匹配数据字段),该行末尾缺失逗号,数组末尾还存在多余的闭合花括号,会导致列解析异常。 - 嵌套对象直接渲染触发报错:你的数据里
Listing是对象类型,如果直接把列key设为Listing,React无法直接把普通对象作为子节点渲染,就会抛出Objects are not valid as a React child错误。 - 属性传值错误:你给
loading传入的是字符串'true'而非布尔值,会导致表格加载态异常常显。
修复步骤
- 修正columns配置的语法错误,通过组件提供的
cell渲染回调提取嵌套对象里的title字段,保证单元格渲染的是基础类型值(字符串/数字),不要直接返回对象。 - 新增loading状态控制,给组件传入正确的布尔类型loading值。
- 修正后完整代码如下:
import React, { Component } from 'react'; import axios from 'axios'; import ReactDatatable from '@ashvin27/react-datatable'; class Products extends Component { constructor(props) { super(props); // 修正列配置语法,新增cell回调处理嵌套字段 this.columns = [ { key: "id", text: "Id", className: "id", align: "left", sortable: true, }, { key: "Listing", text: "Merchant Title", className: "name", align: "left", sortable: true, // 提取嵌套的title字段,空值兜底显示- cell: (record) => record.Listing?.title ?? '-' } ]; this.state = { records: [], loading: false // 新增loading状态 }; this.getData = this.getData.bind(this); } componentDidMount() { this.getData() }; // 注:componentWillReceiveProps已在React16+废弃,如果你不需要props触发刷新可以删掉这段 componentWillReceiveProps(nextProps) { this.getData() } getData() { this.setState({ loading: true }); axios .get("/api/products") .then(res => { this.setState({ records: res.data, loading: false }) }) .catch(err => { console.log('数据拉取失败', err); this.setState({ loading: false }); }) } render() { return ( <div> <ReactDatatable records={this.state.records} columns={this.columns} loading={this.state.loading} // 传布尔值而非字符串 /> </div> ); } } export default Products;
验证说明
- 修复后列会直接读取每条数据
Listing.title的值渲染,不会再把整个Listing对象传给React渲染,从根源解决子节点类型错误。 - loading状态会在请求发起时开启、请求结束后关闭,不会出现常亮问题。
- 空值兜底逻辑可以避免某条数据缺失Listing字段时出现二次报错。
内容的提问来源于stack exchange,提问作者kd12345
相关产品推荐
相关产品推荐

