【问题标题】:Why am I getting 'Cannot read property 'push' of undefined' (React Native)?为什么我会收到“无法读取未定义的属性 'push'”(React Native)?
【发布时间】:2016-07-14 16:35:58
【问题描述】:

在我的 index.ios.js 中,我有以下内容:

  renderScene(route, navigator){
    return <route.component navigator={navigator} {...route.passProps}/>
  }

render() {
    return (
      <Navigator
        initialRoute={{name: 'FirstPage', component: FirstPage}}
        renderScene={this.renderScene}
      />
    );
  }

然后在我的 FirstPage.js 中,导航到 SecondPage.js:

  _navigate(){
    this.props.navigator.replace({
      component: SecondPage,
      name: 'SecondPage'
    })
  }

然后在我的 SecondPage.js 中,它只是将组件呈现在 .在我的 ThirdPage.js 中:

  _rowPressed(){
    this.props.navigator.push({
      component: FourthPage,
      name: 'FourthPage',
    })
  }


  <TouchableHighlight
    onPress={() => this._rowPressed()}
  >
     <View>
          <Text>Go to FourthPage</Text>
     </View>
  </TouchableHighlight>

然后在我的 FourthPage.js 中,我只有:

  <View style={styles.container}>
    This is FourthPage.js
  </View>

我收到来自 ThirdPage.js 的错误,它说:

Cannot read property 'push' of undefined in _rowPressed()

我似乎无法弄清楚为什么,因为 this.props.navigator.push 对 .replace 和 .push 都有效,但现在我收到了这个错误。任何指导或见解将不胜感激。提前谢谢你。

【问题讨论】:

  • push 是数组上的函数,this.props.navigator 是对象。
  • @JohnS Navigator 确实有 push facebook.github.io/react-native/docs/navigator.html
  • OP,您是否将 _rowPressed 方法绑定到构造函数中的组件?
  • @JohnS 据我所知,this.props.navigator.push 适用于对象。
  • @azium 抱歉,您能澄清一下您的意思吗?这就是我的构造函数:constructor(props){ super(props);}

标签: javascript ios react-native react-jsx


【解决方案1】:
<TouchableHighlight
    onPress={this._rowPressed.bind(this)}//add this
  >
     <View>
          <Text>Go to FourthPage</Text>
     </View>
  </TouchableHighlight>

你可能只需要绑定组件

【讨论】:

  • 我试过了,没有错误,但是方法 '_rowPressed*()' 不知何故没有被调用,我似乎无法弄清楚为什么......在 _rowPressed() 中尝试了 console.log即使通过 onPress 调用它,它也没有记录。可能是什么问题?
  • 试试这个 this._rowPressed.bind(this)
  • 实际上它可以正常工作并正确调用方法和日志,但现在我收到以下错误:无法读取未定义的属性'push'
  • navigator.props.push() 试试这个
猜你喜欢
  • 2021-09-12
  • 2021-10-28
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 2019-09-27
  • 2017-10-28
相关资源
最近更新 更多