代码之家  ›  专栏  ›  技术社区  ›  crimsonpython24

Javascript“无法读取React类组件中未定义的属性”

  •  0
  • crimsonpython24  · 技术社区  · 6 年前

    我刚开始反应,当我呈现一个数据集时,我遇到了错误“cannot read property map/0 of undefined”(两个单独的错误, 在代码中注释 ). 真正困扰我的是,当这个州)声明为 const 在类组件之外,所有的功能都很好,但是它不能作为App类的state属性工作。

    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>
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   Ramanpreet Singh    6 年前

    实际上,您正在直接访问levels属性,它是dataSource数组中处于状态的对象的一部分。这就是为什么它给出了未定义的错误 levels

    const levelsArr = this.state.dataSource[0].levels;

    那就试试这样的代码 compare(a.levelsArr[0], b.levelsArr[0])

    阿尔索 {levelsArr && levelsArr.map(level => {