2016-11-09 39 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幷包括處理操作。

希望這適用於您的項目的設置。