【问题标题】:setState in a nested array object for SectionList data by index在嵌套数组对象中为 SectionList 数据按索引设置状态
【发布时间】:2020-01-12 23:16:19
【问题描述】:

我正在尝试用 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 的嵌套数组的索引。

【问题讨论】:

  • 你什么时候做console.log(this.state.sectionListData[0].data),你可以将第二个参数函数传递给setState,看看this.state完成更新后的样子

标签: javascript arrays react-native setstate react-native-sectionlist


【解决方案1】:

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

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)}        
          );
      }
  )};

【讨论】:

  • 为我工作!非常感谢,你让这个外观和声音变得如此简单,但我工作了这么久!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-07
  • 2020-11-02
  • 1970-01-01
  • 2018-12-28
  • 2016-04-29
  • 1970-01-01
  • 2020-03-28
相关资源
最近更新 更多