2017-03-09 67 views
1

我想創建一個像這樣的是否可以在React中創建一個仍然可以訪問全局Redux存儲的類?

class Person { 
    constructor(fname, lname) { 
    this.fname = fname; 
    this.lname = lname; 
    } 
} 

,這樣我可以正常使用喜歡的一類:

let temp = new Person('John', 'Doe'); 

,但有什麼辦法,我可以有一個類訪問全局存儲?

我很樂意做這樣的事情:

class Person { 
    constructor() { 
    this.fname = this.props.fname; 
    this.lname = this.props.lname; 
    } 
} 

function mapStateToProps(state) { 
    return { 
    fname: state.person.fname, 
    lname: state.person.lname 
    }; 
} 
export default connect(mapStateToProps)(Person); 

而是因爲對於一個陣營組件的構造似乎

constructor(props, context) { 
    super(props, context); 
} 

我理解了它可能不是可能呢?但我想問問,因爲它會幫助很多。謝謝

+1

將'this.props'在裏面什麼'新人'? – Bergi

+0

@Bergi如果我可以使用mapStateToProps連接到Redux商店,那麼fname和lname變量將被添加到我的本地道具。添加了「連接」這一行,希望能夠更清楚我想要完成什麼 – user1189352

回答

1

正常類將不會經歷與反應組件相同的生命週期類型,因此connect在這裏沒有意義。

此外,你真的想避免在多個地方存儲相同的狀態。 Redux的全部重點是鞏固國家,併爲您管理。因此,我建議您改爲調用store.getState()在需要知道當前fnamelname,而不是試圖manange Redux的狀態和this.fname之間同步的任何方法,this.lname

要做到這一點,你將不得不暴露當前store通過某種你可能已經在做的import

如果您還沒有這樣做,我建議使用下面的語法

import { createStore } from 'redux'; 
import rootReducer from '../reducers'; 

export let store = null; // placeholder for store singleton once created 

export function init(initialState = {}){ 
    store = createStore(rootReducer, initialState); 
    return store; 
} 

然後從你的個人類,你可以簡單地

import { store } from '../store'; 

function mapStateToProps(state) { 
    return { 
    fname: state.person.fname, 
    lname: state.person.lname 
    }; 
} 

export default class Person() { 
    constructor(){ 
    } 

    toString() { 
     // example method 
     let { fname, lname } = mapStateToProps(store.getState()); 
     return `${fname} ${lname}`; 
    } 
} 
1

不,connect將不適用於這樣的普通類。它僅適用於React組件,因爲它通過道具或上下文訪問商店,並接受/使用React組件。

您需要通過導入直接訪問商店對象。有許多其他公用事業,幫助管理商店訂閱過程 - 也許其中一個可能會幫助你。請參閱我的清單Redux addons catalog: Store - Store Change Subscriptions

也就是說,最終所有真正做的事情都是在某個時候撥打store.subscribe(),並在其訂閱回調中使用store.getState()做些事情。

相關問題