【问题标题】:How to connect component (file) to redux store如何将组件(文件)连接到 redux 存储
【发布时间】:2017-11-21 19:56:17
【问题描述】:

我需要创建 component/file/class 并将其连接到 redux 商店。
我不需要渲染这个组件。
它只是一个辅助组件,可以包含从商店返回值的方法。
我试图创建一个文件:

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

但这只是一个导出功能的文件,我不能(或不知道)如何将它连接到 redux 商店。
我的所有组件都通过以下方式与 store 连接:

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

但正如我所说,这不是场景,它只是我想在整个应用程序中重用的辅助组件。
如何制作这样的组件并将其连接到 redux?

【问题讨论】:

    标签: reactjs react-native redux react-router react-redux


    【解决方案1】:

    Redux 存储有一个名为getState 的方法,它获取存储的状态。可以在需要redux store的文件中导入自己创建的store。

    // 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];
    }

    或者,您可以将 store 传递给 getKeyFromReduxStore 函数,然后在可以使用 store 的 react 组件中调用它。例如在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);

    【讨论】:

      猜你喜欢
      • 2018-08-28
      • 1970-01-01
      • 2020-11-01
      • 2021-01-01
      • 2017-04-12
      • 2021-09-08
      • 1970-01-01
      • 2019-12-26
      • 2017-04-03
      相关资源
      最近更新 更多