【问题标题】:TypeError: undefined is not an object (evaluating 'this.props') - React NativeTypeError: undefined is not an object (evalating 'this.props') - React Native
【发布时间】:2016-07-30 19:52:50
【问题描述】:

当我在获得 json 响应后尝试导航到下一个视图时遇到这种类型的错误。但是如果我在我的 json 响应获取方法之外使用我的this.props.navigator.push({id:'HomeCaseList')} 效果很好。任何人都可以在这里帮助我。

click event

<MKButton
            style={{marginLeft:10, marginRight:10,marginTop:10,marginBottom:350,height:40, width:400}}
            backgroundColor={'#fff'}
            //shadowRadius={2}
            //shadowOffset={{width:0, height:2}}
            shadowOpacity={.7}
            shadowColor="black"
              onPress={
              //  navigator.push();

                this.loginToApp.bind(this)
              }>

login function

gotoNext() {
      fetch('http://url/login/', {
        credentials: 'same-origin',
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          username: 'wasalaa',
          password: 'a',
        })
      }).then(function(response) {
      //console.log(response.headers.get('Content-Type'))
      //console.log(response.headers.get('Date'))
      //console.log(response.status)
      //console.log(response.statusText)
      //console.log('json',response
      //console.log(response.headers.get('JSESSIONID'))
      return response.json()
      }).then(function(json){
      console.log('login response',json)
      if(json.message_code === "SUCCESS"){
        console.log('user logged')
        this.props.navigator.push({
          id: 'HomeCaseList',
          //sceneConfig: Navigator.SceneConfigs.FloatFromBottom,
        });
      }

      }).catch(function(err){
      console.log('error', err)
      })
  }

【问题讨论】:

    标签: javascript json reactjs react-native


    【解决方案1】:

    在回调中this 指的是全局范围(在浏览器中它是window 在node.js 中它是global,如果你使用strict mode 这将是undefined ) 而不是你的组件,你应该设置this

    //....
    .then(function(json) {
      if (json.message_code === "SUCCESS") {
        this.props.navigator.push({
          id: 'HomeCaseList',
          // sceneConfig: Navigator.SceneConfigs.FloatFromBottom
        });
      }
    }.bind(this))
     ^^^^^
    // ....
    

    【讨论】: