2016-11-09 40 views
-2

我在我的React类中有一个方法,但因为我想在我的应用程序的几个类中使用它,所以我将它转换为单独的函数。现在我的问题是,在这个函数中我使用this.setState()并且想在我的类中使用setState。如何从函数中调用setState()如何通过函数调用setState反应

这是我的函数:

export const syncBasketItemsWithServer = (categoriesData, lBasketItem) => { 
    if (categoriesData.has_sub_category) { 
    categoriesData.categories.map((item, index)=> { 
     syncBasketItemsWithServer(item, lBasketItem); 
    }); 
    } 
    if (categoriesData.category_items) { 
    const exist = _.findWhere(categoriesData.category_items, {uid: lBasketItem.uid}); 
    if (exist) { 
     lBasketItem.price = exist.price ? exist.price : categoriesData.price; 
     this.setState({ 
     arr: this.state.arr.concat([lBasketItem]) 
     }); 
    } 
    } 
}; 
+0

你可以添加您的组件的示例代码中所使用的功能? –

+0

它就像你的'SomeClass'类的例子! –

+0

将您的功能更改为仅返回新状态。在组件(类)中保持对'setState'的调用。 –

回答

0

我试试这个:

import _ from 'underscore'; 
    export function syncBasketItemsWithServer(categoriesData, lBasketItem) { 
     if (categoriesData.has_sub_category) { 
     categoriesData.categories.map((item, index)=> { 
      //bind again 
      syncBasketItemsWithServer.call(this, item, lBasketItem); 
     }); 
     } 
     if (categoriesData.category_items) { 
     const exist = _.findWhere(categoriesData.category_items, {uid: lBasketItem.uid}); 
     if (exist) { 
      lBasketItem.price = exist.price ? exist.price : categoriesData.price; 
      this.setState({ 
      syncedItems: this.state.syncedItems.concat([lBasketItem]) 
      }); 
     } 
     } 
    } 
0

为了实现这个目标,你需要的功能与要使用该功能组件的上下文绑定。通过使用call方法和this作为您将函数与当前上下文绑定在一起的第一个参数,因此函数体中的this将引用您的Component。

import { syncBasketItemsWithServer } from '../path/to/file' 

class SomeClass extends Component { 
    someMethod() { 
     syncBasketItemsWithServer.call(this, param1, param2); 
    } 
} 

此外,您还需要重构自己的功能,而无需使用箭头功能,因为他们暗中绑定当前上下文,而你的情况是undefined功能。

export const syncBasketItemsWithServer = function (categoriesData, lBasketItem) { 
    // function body 
} 
+0

tnx的答案,但我尝试这种方式和setState是未定义的... –

+0

哎呀,我的不好...更新了答案 –

+0

tnx再次...我更新我的代码并删除箭头功能,但又setState is undefind :)) –

0

这是不理想的特别调用的setState,理想情况下,你想派遣一个动作,而不是 this.setState() ,然后有一个减速,更新的状态,你依靠什么动作你已派出。

这是一个链接,应该更详细地解释事情http://redux.js.org/docs/basics/Reducers.html并包括处理操作。

希望这适用于您的项目的设置。