我希望从 .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);
我有很多组件,通过connect
附加类,我可以通过connect()
附加函数吗?
最佳答案
编辑 1
Some_File.js
import store from './redux/store.js';
function aFunction(){
var newState =store.getState();
console.log('state changed');
}
store.subscribe(aFunction)
我假设您已经按照 redux 的预期创建了存储和 reducer 。
~~~~~~~~~~~~~~~
原始答案开始
这是一种黑客行为,我不知道你在做什么,所以我不能说你应该或不应该这样做,但你可以这样做。我复制粘贴了您的一些代码并进行了一些修改。
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
。
关于reactjs - 访问函数内部的 redux store,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38986366/