Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

reactjs - Why dispatch in my react app is not working?

I'm using redux for the first time. I'm not much familiar with it.I want to call createTicket function when submit button clicked and for the instance I need to do console log. ticketAction.js

import _ from 'lodash';

import TicketService from './../AddTicketService';
import * as ActionTypes from './../actionTypes/tickets.ActionTypes';

export const createTicket = (formData) => {
  console.log("1");
  return (dispatch) => {
    dispatch({
      type: ActionTypes.CREATE_TICKET_IN_PROGRESS
    });

    console.log(formData);
    const formattedFormData = {
      ...formData,
    };

    TicketService.create(
      formattedFormData
    )
      .then(() => dispatch({ type: ActionTypes.CREATE_TICKET_COMPLETED }))
      .catch((error) =>
        dispatch({
          type: ActionTypes.CREATE_TICKET_FAILED,
          payload: error.response.data
        })
      );
  };
};

It logs 1 in the console.But rest inside the return is not working.

Below is the reducer file ticketsReducer.js

import * as ActionTypes from './../actionTypes/tickets.ActionTypes';
// import _ from 'loadash';

const initialState = {
  createTicketStatus: {
    inProgress: false,
    error: null
  }
};

export default (state = initialState, action) => {
  switch (action.type) {
    case ActionTypes.CREATE_TICKET_IN_PROGRESS:
        console.log('CREATE_TICKET_IN_PROGRESS');
      return {
        ...state,
        createTicketStatus: {
          inProgress: true,
          error: null
        }
      };
    case ActionTypes.CREATE_TICKET_COMPLETED:
      return {
        ...state,
        createTicketStatus: {
          inProgress: false,
          error: null
        }
      };
    case ActionTypes.CREATE_TICKET_FAILED:
      return {
        ...state,
        createTicketStatus: {
          inProgress: false,
          error: action.payload
        }
      };

      default: // need this for default case
      return state 
   
  }
};

question from:https://stackoverflow.com/questions/65880142/why-dispatch-in-my-react-app-is-not-working

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Found the error ! Instead if importing and calling this function createTicket, we have to call it using props. this.props.createTicket(data); If you need more clarifications do let me know!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...