I am working with Redux in React. I had define action & reducer in program. I want to change state by onClick event but its not changing.
This is my code:
import React, { Component, PropTypes } from 'react';
import { createStore } from 'redux';
const display = (state=0, action) => {
switch (action.type){
case 'INCREMENT':
return state+1;
case 'DECREMENT':
return state-1;
default:
return state;
}
};
const store = createStore(display);
store.dispatch({ type: 'INCREMENT'});
var ReduxApp = React.createClass({
plus(){
return store.dispatch({type: 'INCREMENT'});
},
minus(){
return store.dispatch({type: 'DECREMENT'});
},
render(){
return(
<div>
<h1>{store.getState()}</h1>
<button onClick={this.plus}>+</button>
<button onClick={this.minus}>-</button>
</div>
);
},
});
module.exports = ReduxApp;
store.subscribe(() => render(<ReduxApp />));
I tried with subscribe method & re-rendered but its not working.
You're almost there, you haven't connected the rendering to your Redux store, but you're close.
To connect it manually you'd write something like this
store.subscribe(() => render(<MyComponent />, document.querySelector('#container'));
Using your example this should not happen from within the component but from the outside.
var MyComponent = React.createClass({});
store.subscribe();
In a real world scenario you would use something like react-redux and it's Provider component in order to connect the store to your React application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With