TypeError:undefined不是对象(正在评估'this.props')-React Nati

TypeError: undefined is not an object (evaluating 'this.props') - React Native

本文关键字:this props Nati -React 评估 undefined 对象 TypeError      更新时间:2024-04-05

当我在获得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)
      })
  }

在回调中,this指的是全局范围(在浏览器中,它是node.js中的window,它是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))
 ^^^^^
// ....