2017-06-19 55 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);