2017-06-19 54 views
0

我需要創建component/file/class,並將其連接到REDX存儲。
我不需要渲染此組件。
它只是一個幫助器組件,可以包含從存儲中返回值的方法。
我試圖創建一個文件:
如何將組件(文件)連接到REDEX存儲

export function getKeyFromReduxStore(key:string) {... 

,但是這僅僅是一個文件,該文件導出功能,我不能(或不知道),如何將其連接到終極版商店。
我所有的部件都與專賣店throught連接:

<RouterWithRedux> 
      <Scene key="root">... 

但正如我所說,這是沒有場景那就是我想通過整個應用程序重用只是助手組件。
如何製作這樣的組件並將其連接到REDX?

回答

1

Redux商店有一個名爲getState的方法,它獲取商店的狀態。您可以將您創建的商店導入需要使用redux商店的文件中。

// in the file where you created your store 
 
import { createStore } from 'redux'; 
 

 
export const myStore = createStore(
 
    // ... some middleware or reducer etc 
 
) 
 

 
// in your component/file/class 
 
import { myStore } from '../path/to/store' 
 

 
export function getKeyFromReduxStore(key:string) { 
 
    return (myStore.getState())[key]; 
 
}

或者,也可以在店裏傳遞給getKeyFromReduxStore功能,並調用它在反應部件,其中商店將是可用的。例如在mapStateToProps功能:

// component/file/class 
 
export function getKeyFromReduxStore(store, key) { 
 
    return store[key]; 
 
} 
 

 

 
// react component with access to store 
 
import { getKeyFromReduxStore } from '../path/to/file'; 
 

 
class MyKlass extends Component { 
 
    // ... your logic 
 
    render() { 
 
    const val = this.props.getKey(someVal); 
 
    } 
 
} 
 

 
const mapStateToProps = (state) => ({ 
 
    getKey: (key) => getKeyFromReduxStore(store, key), 
 
}) 
 

 
export default connect(mapStateToProps)(MyKlass);