我正在使用useReducer来保存下面的代码中看到的一些状态,但它没有从数组reducer函数返回值。
let [entriesByEmployer, dispatchEntriesByEmployer] = useReducer(
(state, action) => {
const reducer = (employerEntries, entry) => {
console.log("adding to employerEntries");
employerEntries[entry.employerId] = employerEntries[entry.employerId] || [];
employerEntries[entry.employerId].push(entry);
console.log(employerEntries);
return employerEntries;
};
return batchEntries.reduce(reducer, []);
},
[]
);
流程:
- 当我单击屏幕上的按钮时,它会从数据库获取信息
- 该信息存储在批处理条目变量中。
- 我使用 useEffect 在批量条目更改时触发调度条目按雇主
- 这会导致减速器运行。
我知道内部reduce函数运行,因为如果我将其包装在控制台日志中,它将我期望的数据输出到控制台。
console.log(batchEntries.reduce(reducer, []));
但是,当我返回reduce函数的结果时,当我检查组件时,React DevTools显示"Reducer:数组(空)">
问题出在减速器本身。因为我正在分配数组键,所以它没有显示数组。相反,我将其更改为对象
let [entriesByEmployer, dispatchEntriesByEmployer] = useReducer(
(state, action) => {
const reducer = (employerEntries, entry) => {
console.log("adding to employerEntries");
employerEntries[entry.employerId] = employerEntries[entry.employerId] || [];
employerEntries[entry.employerId].push(entry);
console.log(employerEntries);
return employerEntries;
};
return batchEntries.reduce(reducer, {});
},
{}
);