简体   繁体   中英

React redux won't update class component's state

I have a component which is supposed to update if a state from another component has been changed using redux, but it's not.

Inside mapStateToProps the correct value is being returned on redux action.

import React, {Component} from "react";
import './DashboardContent.scss';
import * as entries from '../../../assets/demo.json';

import CategoryHeader from "./CategoryHeader/CategoryHeader";
import NoContent from "../../../shared/NoContent/NoContent";
import UnsortedList from "./UnsortedList/UnsortedList";
import {connect} from "react-redux";

class DashboardContent extends Component {

    state = {
        activeCategory: this.props.activeCategory
    };

    componentDidUpdate(prevProps, prevState, snapshot) {
        console.log(this.props.activeCategory)
    }

    render() {
        return (
            <div>
               ...
            </div>
        )
    }

}

const mapStateToProps = state => {
    console.log(state);
    return {
        activeCategory: state.category
    }
};

export default connect(mapStateToProps)(DashboardContent);



Dispatch inside of another component - when this is being executed, the state activeCategory of first component shall become some value :

dispatch(changeCategory('some value'))



Actions.js

// Action types
const CHANGE_CATEGORY = 'CHANGE_CATEGORY'


// Action creators
export const changeCategory = (category) => {
    return {
        type: CHANGE_CATEGORY,
        category
    }
}



Reducer.js

const initialState = {
  activeCategory: 'all'
};

export const reducer = (state = initialState, action) => {
    console.log('reducer', state, action);
    if (action.type === 'CHANGE_CATEGORY') {
        return action.category
    }
    return state;
};

Your reducer should return the updated state instead it returns action.category atm.

export const reducer = (state = initialState, action) => {
  console.log('reducer', state, action);
  if (action.type === 'CHANGE_CATEGORY') {
   return {...state,category:action.category}; 
  }
  return state;
};

What happens when you add this to the main class?(class DashboardContent extends Component) I believe you need to do that when you try to access the this.props.activeCategory. Try to add this snippet.

 constructor(props) { 
 super(props); 
 this.state = this.props.activeCategory;
 } 

You may refer to this answer: What's the difference between "super()" and "super(props)" in React when using es6 classes?

when you are connecting a component to redux, the second argument is the dispatchToProps, is the only way you can dispatch an action inside your component

export default connect(mapStateToProps, {action1, action2,})(DashboardContent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM