简体   繁体   中英

Redux action not firing - no errors

I'm trying to call a simple action on click which fires a dispatch action. I can't seem to get a result or even indiciation that it's firing.

I'm trying to dispatch on click in a component. I've also tried putting a console.log in the action to see if it even gets fired but it doesn't. Redux dev tools also doesn't suggest it even gets fired on click.

onClick={() => {
   setAQIType(name);
}}

Action:

import { SET_AQITYPE } from "./types";

export const setAQIType = (AQIType) => dispatch => {
    dispatch({
        type: SET_AQITYPE,
        payload: { AQIType }
    });
};

Reducer:

import { SET_AQITYPE } from '../actions/types';

const initialState = {
    aqiType: 'DEFAULT',
    loading: false,
};

export default function(state = initialState, action){

    const { type, payload } = action;

    switch(type){
        case SET_AQITYPE:
            return [...state, payload];
        default:
            return state;
    }

}

Types:

export const SET_AQITYPE = 'SET_AQITYPE';

Three errors,

  1. In reducer: Your state is an object and not a list.
  2. In reducer: Assign payload to aqiType key
  3. In dispatch: Payload is a string and not an object.

To fix:

export const setAQIType = (AQIType) => dispatch => {
    dispatch({
        type: SET_AQITYPE,
        payload: AQIType // (3) pass as string
    });
};

// In reducer
case SET_AQITYPE:
  return { // (1) object
    ...state,
    aqiType: payload // (2) specify aqiType key
  };

This assumes that you've checked the basic example with connect() and mapDispatchToProps .

Most likely you missed to connect the component with the redux store, which means there is no dispatch function passed to your action.

https://react-redux.js.org/using-react-redux/connect-mapdispatch

Cheers

Try to return inside action function as below:

import { SET_AQITYPE } from "./types";

export const setAQIType = (AQIType) => dispatch => {
    return dispatch({
        type: SET_AQITYPE,
        payload: { AQIType }
    });
};

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