我们如何使用useSelector()和useDispatch()使用React-Redux Hooks API创建一个以上的Reducers?

时间:2019-09-16 12:51:05

标签: reactjs react-redux react-hooks

如果我们制造多个reducers,则可以通过使用CombineReducers进行组合,但是当useSelector从哪个reducers获取状态时?

2 个答案:

答案 0 :(得分:1)

从React-Redux docs

const result : any = useSelector(selector : Function, equalityFn? : Function)
  

允许您使用选择器功能从Redux存储状态提取数据

就像mapStateToProps一样,选择器函数接收存储状态,该状态由您所有的reducer合并。

因此,假设您有两个减速器,一个叫counterReducer,另一个叫timeReducer,并且想要从其中一个中获取数据:

const counter = useSelector(state => state.counterReducer.data)

const counter = useSelector({counterReducer} => counterReducer.data)

答案 1 :(得分:0)

useSelector被传递给您的entire Redux store state as its only argument。因此,如果您有两个减速器,它们的命名空间分别为foobar

rootReducer = combineReducers({foo: fooReducer, bar: barReducer})

您可以这样访问它们:

// state is your entire redux store
useSelector((state) => {
  console.log(state.foo);
  console.log(state.bar);
})