首页 > 解决方案 > React类组件中的Javascript“无法读取未定义的属性”

问题描述

简化我是新来的反应,当我渲染数据集时,我收到错误“无法读取未定义的属性映射/0”(两个单独的,在代码中注释)。真正困扰我的是,当 dataSource(在 this.state 中)被声明为const类组件之外时,一切都运行良好,但它不能作为 App 类的状态属性。

function compare(a, b) {
  var n = -1, m = 0;
  if (a === "important") {n = 2;} else if (a === "normal") {n = 1;} else {n = 0;}
  if (b === "important") {m = 2;} else if (b === "normal") {m = 1;} else {m = 0;}
  return n - m;
}

class App extends React.Component {
  state = {
    dataSource: [
      {key: "1", title: "Call Uber eats w/o my parents", levels: ["important"]},
    ],
    count: 2,
  };

  handleAdd = () => {
    const { count, dataSource } = this.state;
    const newData = {
      key: count, name: `Edward King ${count}`, age: 32, address: `London, Park Lane no. ${count}`
    };
    this.setState({dataSource: [...dataSource, newData], count: count + 1});
  };

  render() {
    const columns = [
      {
        title: "Level", dataIndex: "levels", key: "levels",
        sorter: (a, b) => compare(a.levels[0], b.levels[0]),            // cannot read property '0' of undefined
        render: levels => (
          <>
            {levels.map(level => {
              let color = "";                                           // cannot read property 'map' of undefined
              if (level === "important") {color = "red";}
              else if (level === "normal") {color = "blue";}
              return (
                <Tag color={color} key={level}>{level.toUpperCase()}</Tag>
              );
            })}
          </>
        )
      },
    ];
    return (
      <Button onClick={this.handleAdd} type="primary">Add a row</Button>    // Original call
    );
  }
}

我所知道的是,我必须以某种方式从此类的状态中检索数据以防止未定义的属性,但是当我将参数(不是实际对象)传递给函数时我感到困惑,它仍然引发了上述错误。

提前谢谢了。

编辑 这是返回函数的完整代码。这在第一次迭代中不包括在内,现在包括在内(感谢编辑)。

<Row justify="center" align="top">
  <Col style={{ maxWidth: 1080 }}>
    <Space style={{ marginBottom: 16 }}>
      <Button onClick={this.handleAdd} type="primary">
        Add a row
      </Button>
      <Button onClick={this.clearFilters}>Clear filters</Button>
      <Button onClick={this.clearAll}>Clear filters and sorters</Button>
    </Space>
    <Table columns={columns} dataSource={this.state.dataSource}/>
  </Col>
</Row>

标签: javascriptreactjsdictionaryantd

解决方案


实际上,您正在直接访问级别属性,该属性是状态中 dataSource 数组中对象的一部分。这就是为什么它给出 undefined on 的错误levels

在渲染中,先获取状态—— const levelsArr = this.state.dataSource[0].levels;

然后尝试类似这样的代码compare(a.levelsArr[0], b.levelsArr[0])

{levelsArr && levelsArr.map(level => {


推荐阅读