调用操作会更新redux存储中的其他值

时间:2019-07-21 20:13:20

标签: reactjs typescript redux react-redux

我正在从视图中单击按钮来更新redux存储变量的状态。我知道,当有一个调度时,所有的减速器都会被调用。就我而言,当我更新变量的状态时,它将更新另一个变量。

初始状态

enter image description here

更新状态,

enter image description here

这是代码

import React, { Component } from "react";
import {
  Button,
  Container,
  Divider,
  Header,
  List,
  Segment
} from "semantic-ui-react";
import { connect } from "react-redux";
import { StepperDesktop } from "./StepperDesktop";
import { AuthResponse } from "../models/auth-response";
import { IStoreState } from "../redux/reducers";
import { QuoteType } from "../models/enums";
import { quoteTypeActions } from "../redux/actions/quoteType-actions";

interface IGettingStartedProps {
  authResponse: AuthResponse;
  history: any;
  updateQuoteType(quoteType: QuoteType): void;
}

export class _GettingStarted extends Component<IGettingStartedProps> {
  render() {
    return (
      <Container className="abg___main_content_wrapper">
        <StepperDesktop activeStep={1} />
        <Header as="h1">Getting Started</Header>
        <Header as="h3">
          Our online Farm Insurance service allows you to get an instant quote
          for your client that is valid for up to 45 days, but there are policy
          limits and conditions that will apply if you obtain a quote online. If
          you know proposal falls outside of these limits or conditions you
          should still submit your quote request and presentation through this
          service and one of our team will be in contact.
        </Header>
        <Divider hidden />
        <strong>Our online Farm Insurance policy limits:</strong>
        <List bulleted>
          <List.Item>Acreage up to 500 acres</List.Item>
          <List.Item>Farm buildings up to &pound;1,000,000</List.Item>
          <List.Item>Machinery up to &pound;500,000</List.Item>
          <List.Item>Cattle up to &pound;1,000,000</List.Item>
          <List.Item>Sheep up to &pound;1,000,000</List.Item>
          <List.Item>Home buildings up to &pound;1,000,000</List.Item>
          <List.Item>Home contents up to &pound;250,000</List.Item>
          <List.Item>Personal belongings up to &pound;50,000</List.Item>
        </List>
        <Divider hidden />
        <strong>Our online Farm Insurance policy conditions:</strong>
        <List bulleted>
          <List.Item>The current holding insurer in not Aviva;</List.Item>
          <List.Item>
            The proposer, directors or partners in the business have never:
            <List.List>
              <List.Item>
                Been declared bankrupt or insolvent either as private
                individuals or in connection with any business;
              </List.Item>
              <List.Item>
                Been subject of a court judgment in respect of debt either as
                private individuals or in connection with any business;
              </List.Item>
              <List.Item>
                Been officers of a company that has been declared insolvent, or
                had a receiver or liquidator appointed, or entered into
                arrangements with creditors in accordance with the Insolvency
                Act 1986;
              </List.Item>
              <List.Item>
                Been convicted of or charged with but not yet tried for a
                criminal offence other than a motoring offence;
              </List.Item>
              <List.Item>
                Had an insurance contract cancelled or declared void due to a
                breach of a policy condition or due to non-disclosure or
                misrepresentation of a material fact;
              </List.Item>
              <List.Item>
                Within the last 5 years, suffered any loss or made any claim or
                had any claim made against them nor have any accidents occurred
                which are likely to result in a claim being made against them.
              </List.Item>
            </List.List>
          </List.Item>
          <List.Item>
            All insured risks are located at a single premises address;{" "}
          </List.Item>
          <List.Item>
            The buildings insured include no thatched roofs, composite panels
            (unless LPCB approved), glass houses or poly-tunnels;
          </List.Item>
          <List.Item>
            All premises are and will be maintained in a good state of repair;
          </List.Item>
          <List.Item>
            All premises are in an area free from damage by storm or flood;
          </List.Item>
          <List.Item>The premises do not have a reservoir; </List.Item>
          <List.Item>
            All electrical wiring has been tested and inspected in accordance
            with the appropriate guidelines;
          </List.Item>
          <List.Item>
            Not more than 20% of estimated annual revenue is obtained through
            the non-farming and diversified activities listed below, and
            liability cover will not extend to any activity not listed below:
            <List.List>
              <List.Item>Open days farm / house; </List.Item>
              <List.Item>Farm educational visits / farm walks; </List.Item>
              <List.Item>Contracting including Spraying; </List.Item>
              <List.Item>Fishing / fishing rights; </List.Item>
              <List.Item>Shoots - not for profit max 10 guns; </List.Item>
              <List.Item>Rented buildings / loss of rent; </List.Item>
              <List.Item>DIY livery up to 12 horses; </List.Item>
              <List.Item>Caravans / tents; </List.Item>
              <List.Item>Storage of third party boats, caravans; </List.Item>
              <List.Item>Farm weddings / parties; </List.Item>
              <List.Item>Retail (Farm Shops). </List.Item>
            </List.List>
          </List.Item>
        </List>
        <Header as="h3">
          Cover will not extend to any activity not listed above.
        </Header>

        <Divider hidden />
        <Divider hidden />

        <Segment secondary>
          <Header as="h3">
            Click 'Get online quote' to get an instant quote if your proposal
            meets all of the above, or 'Submit request' to upload your
            presentation and request a quote.
          </Header>
          <Container className="app___footer-with-buttons">
            <Button
              primary
              floated="right"
              onClick={() => {
                this.props.updateQuoteType(QuoteType.Simple);
                this.props.history.push("/quote/start-date");
              }}
            >
              Get online quote
            </Button>
            <Button
              basic
              floated="right"
              onClick={() => {
                this.props.updateQuoteType(QuoteType.Complex);
                this.props.history.push("/quote/start-date");
              }}
            >
              Submit request
            </Button>
          </Container>
        </Segment>
      </Container>
    );
  }
}

const mapStateToProps = ({
  authResponse,
  quoteStartDate,
  quoteType
}: IStoreState): {
  authResponse: AuthResponse;
  quoteStartDate: string;
  quoteType: QuoteType;
} => {
  return { authResponse, quoteStartDate, quoteType };
};

const mapDispatchToProps = (dispatch: any) => {
  return {
    updateQuoteType: (quoteType: QuoteType) => {
      return dispatch(quoteTypeActions.updateQuoteType(quoteType));
    }
  };
};

export const GettingStarted = connect(
  mapStateToProps,
  mapDispatchToProps
)(_GettingStarted);

开始日期操作

import { Dispatch } from "redux";
import { StartDateActionTypes } from "./types";

export interface StartDateAction {
  type: StartDateActionTypes;
  payload: string;
}

export const startDateActions = {
  addStartDate: (quoteStartDate: string) => {
    return (dispatch: Dispatch) => {
      dispatch<StartDateAction>({
        type: StartDateActionTypes.ADD_DATE,
        payload: quoteStartDate
      });
    };
  }
};

开始日期缩减器,

import { StartDateActionTypes } from "../actions/types";
import { StartDateAction } from "../actions/startdate-actions";

export const startDateReducer = (
  state: string = "",
  action: StartDateAction
) => {
  switch (action.type) {
    case StartDateActionTypes.ADD_DATE:
      return action.payload;
    default:
      return state;
  }
};

QuoteType操作

import { Dispatch } from "redux";
import { QuoteTypeActionTypes } from "./types";
import { QuoteType } from "../../models/enums";

export interface QuoteTypeAction {
  type: QuoteTypeActionTypes;
  payload: QuoteType;
}

export const quoteTypeActions = {
  updateQuoteType: (quoteType: QuoteType) => {
    return (dispatch: Dispatch) => {
      dispatch<QuoteTypeAction>({
        type: QuoteTypeActionTypes.QOUTE_TYPE_UPDATE,
        payload: quoteType
      });
    };
  }
};

QuoteType reducer

import { QuoteTypeActionTypes } from "../actions/types";
import { QuoteTypeAction } from "../actions/quoteType-actions";
import { QuoteType } from "../../models/enums";

export const quoteTypeReducer = (
  state: QuoteType = QuoteType.Simple,
  action: QuoteTypeAction
) => {
  switch (action.type) {
    case QuoteTypeActionTypes.QOUTE_TYPE_UPDATE:
      return action.payload;
    default:
      return state;
  }
};

组合减速器

import { combineReducers } from "redux";
import { authenticationReducer } from "./authentication-reducer";
import { AuthResponse } from "../../models/auth-response";
import { quoteReducer } from "./quote-reducer";
import { startDateReducer } from "./startdate-reducer";
import { QuoteRequest } from "../../models/quote-request";
import { QuoteType } from "../../models/enums";
import { quoteTypeReducer } from "./quoteType-reducer";

export interface IStoreState {
  authResponse: AuthResponse;
  quoteRequest: QuoteRequest;
  quoteStartDate: string;
  quoteType: QuoteType;
}

export const rootReducer = combineReducers<IStoreState>({
  authResponse: authenticationReducer,
  quoteRequest: quoteReducer,
  quoteStartDate: startDateReducer,
  quoteType: quoteTypeReducer
});

配置存储,

import { createStore, applyMiddleware, StoreEnhancer, compose } from "redux";
import { rootReducer } from "./reducers";
import thunk from "redux-thunk";
import { routerMiddleware } from "react-router-redux";
import { composeWithDevTools } from "redux-devtools-extension";

export const configureStore = (history: any, initialState: any) => {

  const middleware = [thunk, routerMiddleware(history)]; 

  return createStore(
    rootReducer,
    initialState,
    composeWithDevTools(applyMiddleware(...middleware))
  );
};

Index.tsx,

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import { App } from "./App";
import { configureStore } from "./redux/configure-store";
import { Provider } from "react-redux";
import { createBrowserHistory } from "history";
import { Router } from "react-router-dom";

declare global {
  interface Window {
    initialReduxState?: any;
  }
}
const initialState = window.initialReduxState;

const baseUrl = "/";
export const history = createBrowserHistory({ basename: baseUrl });

const store = configureStore(history, initialState);
ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <App />
    </Router>
  </Provider>,

  document.querySelector("#root")
);

App.tsx,

import React from "react";
import "./App.css";
import { IStoreState } from "./redux/reducers/index";
import {
  Button,
  Container,
  Divider,
  Header,
  List,
  Segment
} from "semantic-ui-react";
import { Layout } from "./components/Layout";
import { connect } from "react-redux";
import { AuthResponse } from "./models/auth-response";

interface AppProps {
  authResponse: AuthResponse;
}

export class _App extends React.Component<AppProps> {
  render() {
    return (
      <>
        <Layout />
      </>
    );
  }
}

const mapStateToProps = ({
  authResponse
}: IStoreState): { authResponse: AuthResponse } => {
  return { authResponse };
};

export const App = connect(mapStateToProps)(_App);

不确定在这里我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

解决此问题:

在您的开始日期减少器中,将switch替换为该变量:

  switch (action.type) {
    case StartDateActionTypes.ADD_DATE:
      return {
        ...state, //Return all the values from the current state
        ...action.payload //Overwrite the values that exist in the payload only
      };
    default:
      return state;
  }

用同样的方法固定另一个异径管。