且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

访问函数内部的 redux 存储

更新时间:2023-12-05 23:42:34

编辑 1

Some_File.js

Some_File.js

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

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

store.subscribe(aFunction)

我假设您已经按照 redux 的预期创建了 store 和 reducer.

I am assuming you have created store and reducers as redux expects.

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

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

原始答案开始

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

This is a sort of hack, I don't know what you are doing so I can't say you should or you should not do it, but you can do it this way. I have copy-pasted some of your code with some modifications.

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);

把这个组件放在顶部的某个地方,可能就在provider里面,每当状态改变时,这个组件的这个componentWillReceiveProps就会被调用.

Put this component somewhere at top, may just inside provider, whenever state changes this componentWillReceiveProps of this component will be invoked.