【问题标题】:React Native pass data with react-navigationReact Native 使用 react-navigation 传递数据
【发布时间】:2017-04-18 14:49:34
【问题描述】:

我想在单击按钮时将数据传递到另一个屏幕。我正在使用 router-flux 并且它工作得很好,但是在 react-navigation 上它不会工作。 因此,在 router-flux 上,在单击按钮时,它会调用此函数:

  onSearch() {
    fetch(`URL`, {
        method: 'GET',
        })
      .then((response) => { return response.json() } )
      .then((responseJson) => {
        Action.results({data: responseJson});
      })
      .catch((error) => {
        Alert.alert("0 Cars!");
      });
  }

但是在 react-navigation 上,如果我将代码更改为:

  onSearch() {
    fetch(`URL`, {
        method: 'GET',
        })
      .then((response) => { return response.json() } )
      .then((responseJson) => {
        this.props.navigation.navigate('Resultados', { data: responseJson });
      })
      .catch((error) => {
        Alert.alert("0 Cars!");
      });
  }

它不起作用,我总是收到警报“0 Cars!”。 我究竟做错了什么?在 router-flux 上,它非常简单。

这就是我调用 onSearch 函数的方式:

    <Button onPress={this.onSearch} style={{backgroundColor: '#f48529', width: 140, borderRadius: 30, height: 40}} >
        <Text style={{color: 'white', fontFamily: 'rubik-light', fontSize: 17}}>Search</Text>
        <Icon size={15} name={'search'} color={'white'} />
    </Button>

【问题讨论】:

  • 你做对了,但是如果你在 catch 中传递,你的 ajax 请求就会出错。
  • 什么意思?使用 router-flux,我只会得到“0 Cars!”如果没有数据,但在反应导航中,即使有数据,我也会收到警报并且不会打开下一个屏幕。 @WilomGfx
  • 为什么不试试 console.log(error) 而不是 alert 0 cars。所以你知道错误是什么。
  • 在控制台上出现此错误:无法读取未定义@cjmling 的属性“导航”

标签: javascript react-native react-navigation


【解决方案1】:

尝试将您的 onPress={this.onSearch} 更改为 onPress={this.onSearch.bind(this)}

还有

试试

onSearch() {

    const { navigate } = this.props.navigation;

    fetch(`URL`, {
        method: 'GET',
        })
      .then((response) => { return response.json() } )
      .then((responseJson) => {
        navigate('Resultados', { data: responseJson });
      })
      .catch((error) => {
        Alert.alert("0 Cars!");
      });
  }

【讨论】:

  • 我收到此错误:无法读取未定义的属性“导航”
  • @waze 您是否在我的回答中按上述方式编辑了您的代码?第一个。常量 { 导航 } 行 .. 第二。导航(然后语句中的行?那个错误在哪一行?
  • 是的,我做到了.. 但我也尝试过没有这些更改,错误是一样的。
  • @waze 你能更新你的问题你是如何调用 onSearch 的吗?
  • @waze 我在上面更新了我的答案。尝试绑定这个 onSearch
猜你喜欢
  • 2017-12-19
  • 1970-01-01
  • 2020-12-22
  • 2021-09-16
  • 2022-11-11
  • 2019-10-17
  • 2018-12-13
  • 1970-01-01
  • 2018-12-30
相关资源
最近更新 更多