首页 > 解决方案 > 如何在本机反应中重用 this.setState 和其他组件函数的函数?

问题描述

我不想在我的项目的每个屏幕中都有一个句柄刷新功能,所以我创建了一个Helper.js处理this. 此函数this.setState在屏幕组件内有另一个函数调用。这是我到目前为止得到的,但它返回一个错误。

导出函数

export function handleRefresh(component) {
    const {page, refreshing} = component.state
    component.setState(
      {
        page:1,
        refreshing:true
      },
      () => {
        component.makeRemoteRequest();
      }
    );
  };

我在组件中这样称呼它:

<FlatList
     ...
     onRefresh={()=> handleRefresh(this)}
     refreshing={this.state.refreshing}
     ...
     />

我看到你可以"this"作为参数传递,但错误仍然是undefined.

标签: javascriptreact-native

解决方案


  1. setState shall be within that screen always where you are using FlatList because after making API you have to update and control the state of that screen.
  2. All the states will be in the component where FlatList using.
  3. Use case are not logical in my view. You can try to create a helper function which accepts different functions params like: page, isRefreshing and return the API response and also the API url and datapost will also be dynamic. Because you want to use it in many areas. It will be difficult to maintain.
  4. So, If you like then use redux what you want.

https://snack.expo.io/@prashen/flatlist-onrefresh


推荐阅读