简体   繁体   English

react状态数组对象在render()方法中不可访问

[英]react state array object is not accessible in render() method

Hi i have this wierd problem in which i can access property ooPP on state object but can not access property data of state objects. 嗨,我有一个比较棘手的问题,我可以访问状态对象的属性ooPP ,但不能访问状态对象的属性data the only difference is how they are populated. 唯一的区别是它们的填充方式。

  • state.ooPP is hardcoded state.ooPP是硬编码的
  • state.data is set after calling few functions . 在调用几个函数之后设置state.data

i can see value of state.data as array with one element in react native dev tools but why is this.state.data null in render() ? 我可以在react native dev tools看到state.data值作为带有一个元素的数组,但是为什么render() this.state.data null?

here is the code: 这是代码:

   export default class HomeScreen extends Component {

      _retrieveData = async key => {
        try {
          const value = await AsyncStorage.getItem(key);
          if (value !== null) {
            // We have data!!
            console.log("yay....", value);
            return value;
          }
        } catch (error) {
          // Error retrieving data
        }
      };

      getAllKeys = async () => {
        let keys = [];
        try {
          keys = await AsyncStorage.getAllKeys();
        } catch (e) {
          // read key error
        }

        return keys;
      };



      constructor(props) {
        super(props);

        this.state = {
          data:[],
          kk:'oo',
          ooPP:[{'username':'uuuuu'}]
        }

        this.getAllKeys().then(keys => {
          var promises = keys.map(key => {
            return this._retrieveData(key)
              .then(value => {
                console.log(value, "xx");
                return JSON.parse(value);
              })
              .catch(error => {
//
              });
          });

          Promise.all(promises)
            .then(results => {
              this.state.data=results
            })
            .catch(e => {
//
            });
        });
      }



      renderSeparator = () => {
        return (
          <View
            style={{
              height: 1,
              backgroundColor: "#CED0CE"
            }}
          />
        );
      };

      render = () => {
        return (
          <View>
            <FlatList
              data={this.state.data} //-------> this is not accessible
              ItemSeparatorComponent={this.renderSeparator}
              renderItem={({ item }) => (
                <TOTPItem value={item.username} time={(20 / 30) * 100} />
              )}
            />
            <Text>dd {this.state.kk}</Text>
          </View>
        );
      }
    }
Promise.all(promises)
  .then(results => {              
    this.setState({data: results});
  })
  .catch(e => {
    //
  });
});

You need to use setState to update state. 您需要使用setState更新状态。

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

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