嵌套的React列表不起作用

时间:2017-11-14 19:31:24

标签: javascript reactjs recursion nested-lists

我正在尝试使用React以递归方式将JSON数据呈现到嵌套列表。现在我正在使用这样的简单数据对象:

[{"id": "1",
 "name": "Luke"
},
{"id": "2",
 "name": "Jim",
  "childNodes":[{
    "id": "3",
    "name": "Lola"
   }]
}]

使用这个类:

export default class NestedList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: true
    };
  }

  toggle = () => {
    this.setState({ visible: !this.state.visible });
  };

  renderChild = (child) => {
    if (child.childNodes) {
      return (
        <ul>
          {child.myData.map(item => {
            return this.renderChild(item);
          })}
        </ul>
      );
    }
    else if (child.name) {
      return <input type="checkbox"><Child name={child.name}/></input>;
    }
    return null;
  }


  render() {
    return (
      <aside>
        <div>
          <h4>Data Sets</h4>
          <ul>
            {this.renderChild(this.props.myData)}
          </ul>
        </div>
      </aside>
    );
  }
}

调用创建list元素的Child类:

export default class Child extends Component {
  render() {
    let {name}=this.props;
    return (
      <li>{name}</li>
    );
  }
}

但它不会打印任何内容。我已经尝试完全删除属性childNodes并尝试打印列表但它仍然不起作用。我不明白我做错了什么。关于如何解决这个问题,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

首先需要通过myData进行映射,以便开始渲染过程:

<ul>
  {this.props.myData.map(data => this.renderChild(data))}
</ul>

此外,在childNodes上,您需要遍历child.childNodes

if (child.childNodes) {
  return (
    <ul>
      {child.childNodes.map(node => this.renderChild(node))}
    </ul>
  );
}

答案 1 :(得分:0)

这里有几个问题:

  1. 您已将myData传递给renderChild,但childNodes未成立name 属性和myData属性。因此没有满足任何条件 (返回null) 所以也许你应该遍历renderChild和 将数组的每个成员传递给renderChild
  2. 即使我们将有效的“孩子”传递给if (child.childNodes) { 方法, 在这种情况下:

    <ul>
      {child.myData.map(item => {
      return this.renderChild(item);
      })}
    </ul>
    

    你再次使用了错误的属性:

    {child.childNodes.map(item => {...
    

    这应该是:

    input
  3. 最后,您无法将子元素嵌套在 <input type="checkbox"/> <Child name={child.name} /> 元素中。 所以改变布局,也许是这样的? :

    const data = [
      {
        id: "1",
        name: "Luke"
      },
      {
        id: "2",
        name: "Jim",
        childNodes: [
          {
            id: "3",
            name: "Lola"
          }
        ]
      }
    ];
    
    class NestedList extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          visible: true
        };
      }
    
      toggle = () => {
        this.setState({ visible: !this.state.visible });
      };
    
      renderChild = child => {
        if (child.childNodes) {
          return (
            <ul>
              {child.childNodes.map(item => {
                return this.renderChild(item);
              })}
            </ul>
          );
        } else if (child.name) {
          return (
            <div>
              <input type="checkbox"/>
              <Child name={child.name} />
            </div>
          );
        }
        return null;
      };
    
      render() {
        return (
          <aside>
            <div>
              <h4>Data Sets</h4>
              <ul>{this.props.myData.map(item => this.renderChild(item))}</ul>
            </div>
          </aside>
        );
      }
    }
    
    class Child extends React.Component {
      render() {
        let { name } = this.props;
        return <li>{name}</li>;
      }
    }
    
    ReactDOM.render(<NestedList myData={data} />, document.getElementById("root"));
  4. 以下是您的代码的运行示例:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="root"></div>
    #include <QCoreApplication>
    #include <QtSql/QSqlDatabase>
    #include <QtSql/QSqlQuery>
    #include <QDebug>
    
    int main(int argc, char *argv[])
    {
       QCoreApplication a(argc, argv);
    
        //use mysql driver
        QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    
        //set hostname
        db.setHostName("localhost");
    
        //set db name
        db.setDatabaseName("test");
    
        //set username and password
        db.setUserName("user");
        db.setPassword("pass");
    
        //open db
        bool ok = db.open();
    
        qDebug() << "Db is open: " << ok;
    
        //define a query
        QSqlQuery query;
        //set query
        query.exec("SELECT * FROM `Persons`");
    
        //get values from query
        while (query.next()) {
                QString LastName = query.value(1).toString();
                QString  FirstName = query.value(2).toString();
                int age = query.value(3).toInt();
                qDebug() << LastName << " " << FirstName << " " << age;
            }
    
        //close db
        db.close();
    
      return a.exec();
     }