Kirit Modi
Kirit Modi

Reputation: 23407

Reload render issue after change props using Redux?

I use the redux in my apps. there is only one state is define. I can change the state and render the screen. but whenever i change state props I can't reload the screen.

Code:

action-types.js

export const SET_NOTIFICATION = "SET_NOTIFICATION";

action.js

import {
    SET_NOTIFICATION,
} from "./action-types";

let initialState = {
    notyIndex: 0,
};

export const setNotyIndex = (notyIndex) => ({type: SET_NOTIFICATION, notyIndex});

reducer.js

import {
    SET_NOTIFICATION,
} from "./action-types";

let initialState = {
    notyIndex: 0,
};

export default reducer = (state = initialState, action) => {
    switch (action.type) {
        case SET_NOTIFICATION:
            return Object.assign({}, state, {notyIndex: action.notyIndex});
            break;
        default:
            return initialState;
            break;
    }
};

I connect the redux as below. DashBoard.js

import { setNotyIndex } from "./action";
import {connect} from "react-redux"

********* LIFE CYCLE START ************

 componentWillMount(){
  console.log('Call update');
  console.log('Index is',this.props.notyIndex);
 }

 shouldComponentUpdate=()=>{
    return true
  }
 componentDidUpdate=(prevProps, prevState, snapshot)=>{
    console.log('Call update');
    console.log('Index is',this.props.notyIndex);
  }

 componentDidMount() {
     console.log('Call update');
     console.log('Index is',this.props.notyIndex);
  }

********* LIFE CYCLE END ************

const mapDispatchToProps = (dispatch) => {
  return {
      setNotyIndex: (notyIndex) => dispatch(setNotyIndex(notyIndex)),
  }
};

const mapStateToProps = (state) => {
    if (state === undefined) {
        return {};
    }
    return {
        notyIndex: state.notyIndex,
    }
};


connect(mapStateToProps, mapDispatchToProps)(DashBoard);

value is set like.

setNotyIndex(1);

- As above code the no one lifecycle method called after set the value.

Thanks.

Upvotes: 0

Views: 372

Answers (1)

Harpal Singh Jadeja
Harpal Singh Jadeja

Reputation: 11

First when you use redux's Method you must call with

this.props.setNotyIndex(1);

and When you use redux's veriable in your component you must have you use

this.props.notyIndex

You can console in your mapStateToProps method to get changes like under

const mapStateToProps = (state) => {
console.log("State veriable : ", state)
if (state === undefined) {
    return {};
}
return {
    notyIndex: state.notyIndex,
}

};

When you change your redux veriable and if you use that veriable in your code then relative component rerender it selt. But if there some issue then you can call setState menually after redux method calling, like under

this.props.setNotyIndex(1);
this.setState({

});

I hope it work for you.......

Upvotes: 1

Related Questions