reactjs - 单独使用 reducer 可以正常工作,但使用 combineReducers 后,就不工作了?

2020-04-29 17:30:50 +08:00
 yazoox
import rootReducer from "./reducers";
import itemReducer from "./reducers/itemReducer";
import rootSaga from "./Sagas";

const sagaMiddleware = createSagaMiddleware();
const enhancer = composeWithDevTools(applyMiddleware(sagaMiddleware));

const store = createStore(rootReducer, enhancer); // 不能工作
// const store = createStore(itemReducer, enhancer); //可以正常工作

sagaMiddleware.run(rootSaga);

reducers/index.js

import { combineReducers } from "redux"
import itemReducer from "./itemReducer"

const rootReducer = combineReducers({
    itemReducer
 })

 export default rootReducer;

如上所示, 如果我 createStore 传 rootReducer,我的项目就不工作。 但是,如果我 createStore 传 itemReducer,就可以正常工作。

是我的 combineReducers 调用不正确。还是说,当使用 combineReducers 后,我应该在其它地方做相应的修改么? 我 debug 了一下,console.log(store.getState()),好像和只调用一个 itemReducer 时不一样, 不是很清楚,比如 mapStateToProps,等地方是不是也要修改(或者如何修改)?我有好多 map... 那不都得修改?

谢谢!

1064 次点击
所在节点    程序员
6 条回复
noobma
2020-04-29 17:42:05 +08:00
不懂 react-redux,不过你想要打平的话,用 {...itemReducer} 这种写法应该就好了,但是你有好多,不知道会不会冲突😂😂
sleepwalker
2020-04-29 17:55:53 +08:00
"项目就不工作"是什么个情况?
l1nyanm1ng
2020-04-29 18:16:31 +08:00
肯定要修改,现在你使用了 combineReducers,原本在 mapStateToProps 的地方想要取出 itemReducer 的状态,都需要加一个命名空间 itemReducer,
比如原来你 itemReducer 的结构为 { "color": "string", nested: { count: 2, array: [] } },未使用 combineReducers 时,mapStateToProps 只需要写成 rootState => ({ color: rootState.color, count: rootState.nested.count }),
现在你用 combineReducers 就是将 itemReducer 加了一个命名空间了,现在的 mapStateToProps 需要这么写 rootState => ({ color: rootState.itemReducer.color, count: rootState.itemReducer.nested.count }),

顺便补一句,现在 hooks 这么好用,你怎么还在用 react-redux 的 connect 高阶函数,直接用 react-redux 的 useSelector 太香了,还有 saga 用得感觉算小众了,直接 redux-thunk 比较简单
yazoox
2020-04-29 18:17:13 +08:00
@sleepwalker
@noobma

搞定了!就是调用 mapStateToProps(state) => {index = state.index} 的参数 state 时,也需要对应修改
以前是
state.index
现在是
state.itemReducer.index

可以给 itemReducer 命个别名,读起来更容易一些。

这可真是绕啊......
yazoox
2020-04-29 18:22:41 +08:00
@l1nyanm1ng 谢谢解答

我们项目 /产品是三年前的,已成型了,很多用法都是以前的。使用 redux 管理数据存储和共享 ,用 saga 解决异步调用。(我要是有能力 refactor architecture 的话...... )

我是最近才开始学习的,前端变化太快了,这才三年啊......

另,redux-saga 好像就是因为 redux-thunk 不太好用,才设计出来的吧?
l1nyanm1ng
2020-04-29 18:34:05 +08:00
@yazoox 确实是,redux-saga 是为了解决以前 redux-thunk 内回调函数写法才萌生的,但是 generator 的写法已经有后来的 async/await 写法完美替代了,generator 写法感觉是一种中间过渡态的解决方案,我感觉 generator 理解起来还是挺难的

anyway,一切维稳最重要!不加工资不出问题就不用动以前的代码了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/667348

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX