当Reducer在React中返回“状态”时会发生什么?

时间:2020-06-04 13:20:36

标签: reactjs redux react-redux

如果我有一个如下所示的contactReducer:

import {
  GET_CONTACTS,
  DELETE_CONTACT,
  ADD_CONTACT,
  EDIT_CONTACT,
  GET_CONTACT,
} from "../actions/types";

// the state the holds the contacts
const initialState = {
  contacts: [
    {
      id: 1,
      name: "John Doe",
      email: "john@gmail.com",
      phone: "555-555-5555",
    },
    {
      id: 2,
      name: "Karen Williams",
      email: "karen@gmail.com",
      phone: "444-444-4444",
    },
    {
      id: 3,
      name: "Henry Johnson",
      email: "henry@gmail.com",
      phone: "333-333-333",
    },
  ],
  contact: {},
  testProp: {},
};

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_CONTACTS:
      console.log("get contacts");
      return {
        ...state,
      };
    case DELETE_CONTACT:
      return {
        ...state,
        contacts: state.contacts.filter(
          (contact) => contact.id !== action.payload
        ),
      };
    case ADD_CONTACT:
      let newArray = state.contacts.slice(); // get the current contacts array
      newArray.unshift(action.payload); //push on the new contact to the beg of array
      return {
        ...state, //take the existing state..
        contacts: newArray,
      };
    case EDIT_CONTACT:
      console.log("trying to edit");
      return {
        ...state,
        contacts: state.contacts.map((contact) =>
          contact.id == action.id ? (contact = action.payload) : contact
        ),
      };

    case GET_CONTACT:
      const selectedContact = getSingleContactFromId(state, action.payload);
      console.log("look here");
      console.log(selectedContact);
      return {
        ...state,
        contact: selectedContact,
        testProp: { test: "test prop" },
      };

    default:
      console.log("testing action in default");

      return state;
  }
}

function getSingleContactFromId(state, id) {
  var contact;
  console.log("get single contact");
  for (var i = 0; i < state.contacts.length; i++) {
    contact = state.contacts[i];
    if (contact.id == id) {
      return contact;
    }
  }
}

减速器返回时实际上发生了什么?它回到哪里?例如,我像这样this.props.addContact(newContact); 向减速器发送调度 但是,在此之后的任何地方,我都看不到对返回的对象执行任何操作。在另一个文件中,我是从状态中获取内容的地方,所以返回真的只是意味着它正在更新状态吗?

1 个答案:

答案 0 :(得分:1)

假设您使用combineReducers,则从特定化简器返回的state现在将是该化简器表示的状态块的更新状态。 然后,任何connected组件都将收到新状态并重新渲染。

这显然是一个高级描述。

更多信息可以在这里找到:https://react-redux.js.org/using-react-redux/connect-mapstate