Answer the question
In order to leave comments, you need to log in
How to subscribe to events from a component in Redux?
How to subscribe to events from a component in Redux?
CREATE-REACT-APP is used for development.
All the answers we have found are about a more simplified project structure.
store.subscribe(() => {
console.log(store.getState().lastAction);
});
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk from 'redux-thunk'
import { Router, Route, hashHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
import App from './App'
import reducer from './reducers'
const store = createStore(reducer, composeWithDevTools(applyMiddleware(thunk)));
const history = syncHistoryWithStore(hashHistory, store);
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App} />
</Router>
</Provider>,
document.getElementById('root')
);
export default function reducer1(state = initialState, action) {
switch (action.type) {
default: {
return state;
}
export const action1 = (data) => dispatch => {
dispatch({ type: 'EVENT1', payload: {value1:1} })
}
export const action2 = (data) => dispatch => {
dispatch({ type: 'EVENT2', payload: {value2:2} })
}
import * as action1 from './actions/action1';
import * as action2 from './actions/action2';
class App extends Component {
componentDidMount() {
this.props.state.reducer1.subscribe( ()=>{
/*мои представления о работе подписки, тут мы имеем доступ к EVENT1 и EVENT2*/
} )
}
render() {
return (<div></div>)
}
}
export default connect(
(state, props, ownProps) => ({
state: state,
props: props
}),
actions1,actions2
)(App)
Answer the question
In order to leave comments, you need to log in
It seems to me that you need to look towards the middleware and make a wrapper in which you can already call the necessary actions
const MyMiddleware = store => next => action => {
switch(action.type) {
case 'SOME_EVENT_TYPE': {
store.dispatch(action)
}
default:
return next(action)
}
}
You are going the wrong way, you have an architectural error. Why subscribe from a component to an action? Let the action change something in the Redux store and the updated data comes to the component.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question