首页 > 解决方案 > React native - 将函数导入使用“this”的组件

问题描述


我有一个名为 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, 

标签: reactjsreact-native

解决方案


一旦你将函数移出组件,它的this上下文就不再是 React 组件。我建议将您要引用的状态传递给函数

function getGooglePlaces(componentState) => {
  ...


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

然后使用函数返回的结果设置组件的状态

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

希望有帮助!


推荐阅读