为什么我会遇到“Cannot read property 'push' of undefined”错误(React Native)?

4

在我的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 中,它只是在一个 div 中呈现组件。而在我的 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是一个对象。 - John S
@JohnS Navigator确实有push功能 https://facebook.github.io/react-native/docs/navigator.html - azium
OP,你在构造函数中是否将 _rowPressed 方法绑定到组件了? - azium
据我所知,this.props.navigator.push适用于对象。 - Jo Ko
@azium 抱歉,您能澄清一下您的意思吗?这是我的构造函数:constructor(props){ super(props);} - Jo Ko
@JoKo TIL。有趣。 - John S
1个回答

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

你可能只需要绑定组件


我尝试了一下,没有错误,但是'_rowPressed*()'方法似乎没有被调用,我无法弄清楚为什么...在_rowPressed()内尝试console.log,即使通过onPress调用它也不会记录。可能是什么问题? - Jo Ko
尝试使用 this._rowPressed.bind(this)。 - Burak Karasoy
实际上它可以正常工作并调用方法并正确记录日志,但现在我遇到了以下错误:无法读取未定义的属性“push”。 - Jo Ko
navigator.props.push() 试一下。 - Burak Karasoy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接