Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in state change

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.

like image 616
maharshi oza Avatar asked Apr 19 '26 01:04

maharshi oza


1 Answers

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.

like image 125
Henrik Andersson Avatar answered Apr 21 '26 15:04

Henrik Andersson