反应本机-导入功能到使用“ this”的组件

时间:2019-04-03 02:18:02

标签: reactjs react-native


我有一个名为getGooglePlaces ....的函数,该函数当前位于表示组件的类中。 它非常复杂,因此我想将其移至其他文件(帮助文件)并导入。 但是我收到错误消息“无法读取未定义的属性'刷新'”。
我假设它指的是“ this” ....那么我该怎么做,以便我的组件从被导入的函数中识别出“ this”? (就像“ this”属于导入它的组件一样)

  getGooglePlaces = () => {

    //add loading spinner unless we are refreshing
    if (this.state.refreshing === false) this.setState({ loading: true });

    //hit google places api
    const uri = `etcetc`;

    fetch(uri)
      .then(resp => resp.json())
      .then((dataBack) => {
        this.setState({
          data: uniqueDataArray,
          loading: false, 
          refreshing: false, 

3 个答案:

答案 0 :(得分:1)

将函数移出组件后,其this上下文将不是React组件。我建议将要引用的状态传递给函数

function getGooglePlaces(componentState) => {
  ...


  return { 
    data: uniqueDataArray,
    loading: false, 
    refreshing: false
  }
}

然后设置组件的状态以及函数返回的结果

class MyReactComponent extends Component {
  ...
  const result = getGooglePlaces(this.state)
  this.setState(result)
  ...
}

希望有帮助!

答案 1 :(得分:1)

您的范围是指它以前所在的类实例。由于您已将函数转移到类范围之外,因此该函数不再有权访问this

一种方法是将this的实例传递到函数调用中。

在您的班级内部,您可以像下面这样呼叫:

    getGooglePlaces(this);

另一种方法就是重构getGooglePlaces以接受如下所示的回调函数:

function getGooglePlaces(callback) {

    //hit google places api
    const uri = `etcetc`;

    fetch(uri)
      .then(resp => resp.json())
      .then((dataBack) => {
        callback(dataBack); // passed to calling scope
    }
}

在课堂上像下面这样称呼它:

if (this.state.refreshing === false) this.setState({ loading: true });


getGooglePlaces(function(uniqueDataArray) { // received when callback called 
    this.setState({
      data: uniqueDataArray,
      loading: false, 
      refreshing: false
    })
})

通过这种方式,您可以将this保留在适当的范围内,而无需通过它。

答案 2 :(得分:0)

感谢你们俩。我实际上最终使用了第三种方法。...我将以下代码行添加到构造函数中,效果很好

this.getGooglePlaces = getGooglePlaces.bind(this);