繁体   English   中英

按索引在 SectionList 数据的嵌套数组对象中设置状态

[英]setState in a nested array object for SectionList data by index

我正在尝试用 SQLite 数据库中的数据填充 SectionList。

我从这里开始:

  constructor(props) {
    super(props);
      this.state = {
        loading: true,
        sectionListData: [
          {
            title: 'A Bulls',
            data: []
          },
          {
            title: 'H Bulls',
            data: []
          },
          {
            title: 'C Bulls',
            data: []
          },
          {
            title: 'R Bulls',
            data: []
          }
        ]
      };
    }

我从数据库中获取数据,当我将 setState 转到适当的位置时,它不需要。

componentDidMount() {
    this.aBulls();
    this.cBulls();
    this.hBulls();
    this.rBulls();
}

每个函数的构建都是相同的,从各自的数据库中获取数据:

aBulls() {
  db.transaction(
    tx => {
    //SQL Statement
        tx.executeSql("select * from abulls group by reg",
    //Arguments
        [],
    //Success
        (tx, { rows: {_array} }) => {
          const handlebull = JSON.stringify(_array);
          const bulls = JSON.parse(handlebull);
          this.setState({sectionListData: [
            {
              0: 
                {
                  data: bulls
                }
            }
          ]
          });
          this.setState({loading: false});
        },
    //Error
        (error) => {console.log(error)}        
          );
      }
  )};

console.log(bulls) 将按预期返回数据数组。 console.log(this.state.sectionListData[0].data) 将返回“未定义”。 我看不到它来更新 SectionList 的嵌套数组的索引。

也许您应该先设置一个局部变量来保存当前状态,然后从该局部变量更新状态

aBulls() {
  db.transaction(
    tx => {
    //SQL Statement
        tx.executeSql("select * from abulls group by reg",
    //Arguments
        [],
    //Success
        (tx, { rows: {_array} }) => {
          const handlebull = JSON.stringify(_array);
          const bulls = JSON.parse(handlebull);
          let sectionListData = this.state.sectionListData;
          sectionListData[0].data = bulls;
          this.setState({sectionListData, loading: false});
        },
    //Error
        (error) => {console.log(error)}        
          );
      }
  )};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM