React Native - this.state未定义

时间:2018-04-02 14:05:45

标签: reactjs react-native

我有一个反应原生的组件,如下所示

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { PermissionsAndroid } from "react-native";
import SmsAndroid  from 'react-native-get-sms-android';

var filter = {
    box: 'inbox', // 'inbox' (default), 'sent', 'draft', 'outbox', 'failed', 'queued', and '' for all
    // the next 4 filters should NOT be used together, they are OR-ed so pick one
    read: 1, // 0 for unread SMS, 1 for SMS already read
    // _id: 1234, // specify the msg id
    // address: '+1888------', // sender's phone number
    // body: 'How are you', // content to match
    // the next 2 filters can be used for pagination
    indexFrom: 0, // start from index 0
    maxCount: 10, // count of SMS to return each time
};

export default class App extends React.Component {


  constructor(props) {
    super(props);
    this.state = {messages : {}, count: 0}
  }

  componentDidMount() {
    console.log(" => Component is mounted")

    SmsAndroid.list(JSON.stringify(filter), (fail) => {
            console.log("Failed with this error: " + fail)
        },
        (count, smsList) => {
            console.log('Count: ', count);
            console.log('List: ', smsList);
            var arr = JSON.parse(smsList);

            this.setState({
              messages:arr,
              count:count
            })

            arr.forEach(function(object){
                console.log("Object: " + object);
                console.log("-->" + object.date);
                console.log("-->" + object.body);
            })
        });

  }

  componentWillUnMount () {
    console.log("Component will be unmounted")
  }

  render() {
    return (
      <View style={styles.container}>

        <Text>Open up App.js to start working on your app!</Text>
        <Text className="imp">{this.state.count}</Text>
        <Text className="imp">{typeof(this.state.messages)}</Text>
        {Object.keys(this.state.messages).map(function(key) {
          <Text className="imp">{this.state.messages[key]}</Text>
        })}

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  imp : {
    color:'#e74c3c'
  },
});

那就是说,代码在我这样做时有用

<Text className="imp">{this.state.count}</Text>
<Text className="imp">{typeof(this.state.messages)}</Text>

但是当我尝试循环播放消息时它失败了

{Object.keys(this.state.messages).map(function(key) {
  <Text className="imp">{this.state.messages[key]}</Text>
})}

它失败并显示以下消息

enter image description here

请告诉我我的代码中有什么问题?

由于 GAGAN

1 个答案:

答案 0 :(得分:0)

您创建一个匿名函数,其中this关键字将指向Object,这是此匿名函数:

{Object.keys(this.state.messages).map(function(key) {
    <Text className="imp">{this.state.messages[key]}</Text>
})}

我看到你可以使用箭头功能,所以把它改成:

{Object.keys(this.state.messages).map((key) => {
    <Text className="imp">{this.state.messages[key]}</Text>
})}

箭头函数将使用定义它的上下文。

更多关于“this”和MDN中的函数。