react-native TypeError: undefined 不是一个对象(评估'this.props.navigator.push')

IT技术 android reactjs react-native
2021-05-25 17:43:41

我正在尝试这个适用于 android 的 react-native 教程:https : //www.raywenderlich.com/126063/react-native-tutorial

我在使用导航器时遇到问题。第一个屏幕(SearchPage)工作正常,但是当尝试 .push 到下一个屏幕时,它给了我以下错误:

发生了一些不好的事情 TypeError: undefined is not an object (evaluating 'this.props.navigator.push')

主要的:

render () {
 return(
  <Navigator
    initialRoute={{id: 'SearchPage'}}
    renderScene={this.renderScene.bind(this)}
    />
 );
}

renderScene(route, navigator) {
 switch (route.id) {
  case 'SearchPage':
   return (
    <SearchPage navigator={navigator} />
   );
   case 'TestScreen':
    return (
     <TestScreen navigator={this.props.navigator} />
   );}

搜索页面:

_executeQuery(query) {
 this.setState({ isLoading: true });
 fetch(query)
  .then(response => response.json())
  .then(json => this._handleResponse(json.response).bind(this))
  .catch(error =>
     this.setState({
      isLoading: false,
      message: 'Something bad happened ' + error
   }));
}

_handleResponse(response) {
  this.setState({ isLoading: false , message: '' });
  if (response.application_response_code.substr(0, 1) === '1') {
    this.props.navigator.push({
      id: 'TestScreen',
    });
  } else {
    this.setState({ message: 'Location not recognized; please try again.'});
  }
}

提前致谢!

1个回答

我认为这是一个范围问题。尝试使用 es6 胖箭头:

renderScene = (route, navigator) => {
 switch (route.id) {
  case 'SearchPage':
   return (
    <SearchPage navigator={navigator} />
   );
   case 'TestScreen':
    return (
     <TestScreen navigator={navigator} />
   );
}

请注意,我在 TestScreen 案例中通过导航器更改了 this.props.navigator。

_executeQuery = (query) => {
 this.setState({ isLoading: true });
 fetch(query)
  .then(response => response.json())
  .then(json => this._handleResponse(json.response))
  .catch(error =>
     this.setState({
      isLoading: false,
      message: 'Something bad happened ' + error
   }));
}

_handleResponse = (response) => {
  this.setState({ isLoading: false , message: '' });
  if (response.application_response_code.substr(0, 1) === '1') {
    this.props.navigator.push({
      id: 'TestScreen',
    });
  } else {
    this.setState({ message: 'Location not recognized; please try again.'});
  }
}