reactjs - 当 reducer 在 React 中返回“状态”时会发生什么?
问题描述
如果我有一个如下所示的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);
但是,我没有看到我在此之后的任何地方对返回的对象做任何事情。在另一个文件中,是我从状态中获取东西的地方,那么 return 真的只是意味着它正在更新状态吗?
解决方案
假设您使用combineReducers
,state
从特定减速器返回的现在将是此减速器表示的状态块的更新状态。然后,任何connected
组件都会收到新的状态并重新渲染。
这显然是一个高级描述。
更多信息可以在这里找到:https ://react-redux.js.org/using-react-redux/connect-mapstate
推荐阅读
- algorithm - 如何从运行总数中添加或减去数字,使其遵循随机给定的指令
- wso2 - WSO2 EI - 处理 SFTP 错误并调用故障/错误序列
- angular - 使用 Prisma 和 Apollo 调用多个 GraphQL 突变的正确方法是什么
- html - 如何使 Bootstrap 列占据主要高度?
- rrdtool - RRDTool 数据值(例如最大值)在不同的时间分辨率下是不同的
- java - 如何使用 EventChannel 从本机服务的 BroadcastReciever 接收数据流?
- mysql - 在 MySQL 中将 GenerationType.SEQUENCE 与 Hibernate 一起使用是个好主意吗?
- vb.net - 如何确定一个变量是否大于Visual Basic中的2个其他变量
- agda - 在 Agda 中,我如何证明在 uncons over coinductive list(aka Stream)之后的 cons 是身份?
- python-3.x - 在 Pandas 数据框中定义递归函数