访问函数内的redux store

raa*_*ne7 15 reactjs redux react-redux

我希望从.js文件中公开一个函数,在该函数中我更愿意访问商店中的变量.

代码片段: -

import { connect } from 'react-redux';

function log(logMessage) {
    const {environment} = this.props;
    console.debug('environment' + environment + logMessage ); 
    ....
}

function mapStateToProps(state) {
    return {
        environment : state.authReducer.environment
    };
}

export default function connect(mapStateToProps)(log);
Run Code Online (Sandbox Code Playgroud)

我有很多组件,通过附加类connect,我可以附加功能connect()吗?

Pra*_*sad 15

编辑1

Some_File.js

import store from './redux/store.js';

function aFunction(){
   var newState =store.getState();
   console.log('state changed');
}

store.subscribe(aFunction)
Run Code Online (Sandbox Code Playgroud)

我假设你已经按照redux的预期创建了商店和减速商.

~~~~~~~~~~~~~~~

原始答案开始

这是一种黑客,我不知道你在做什么,所以我不能说你应该或你不应该这样做,但你可以这样做.我已经复制了一些代码并进行了一些修改.

Class XYZ extends React.Component{
     componentWillReceiveProps(props){
       //in your case this.props.storeCopy is redux state.
      //this function will be called every time state changes
     }

     render(){
        return null;
     }
}



function mapStateToProps(state) {
    return {
        storeCopy : state
    };
}

export default function connect(mapStateToProps)(XYZ);
Run Code Online (Sandbox Code Playgroud)

把这个组件放在顶部,可能只是在里面provider,只要状态改变componentWillReceiveProps,就会调用这个组件.


kar*_*mar 5

如果你有一个纯函数式组件,那么你可以像这样直接访问 redux 状态:

import store from './redux/store';

function getStoreDetails() {
   console.log(store.getState());
}
Run Code Online (Sandbox Code Playgroud)