Reducer如何更新商店

问题描述 投票:0回答:3

我是Redux的新手,我发现了一些理解reducers概念的问题,我可以看到许多例子显示它需要当前状态并返回更新状态,我的问题是它如何通过返回新状态来更新Store(我发现很难了解机制),有人可以解释一下。

reactjs redux reducers
3个回答
4
投票

this is not my image

这是我在学习相同概念时发现非常有用的图像。


Dispatch

当您调度任何函数时,它将转到所有reducers,如果调度类型匹配,它将更改该reducer的状态。

 functionName:()=>(dispatch)({type:'some-thing-to-match',payload})


Reducers That handle state change.


Store Combination of all the reducers (root reducer).
const store = combineReducers({
Reducer1:r1,
Reducer2:r2,
Reducer3:r3
})


For example take the dispatch function in TodoList that matches in r1 and changes its state.Then by connect from 'react-redux' we will connect that reducers state to TodoList.
var mapStateToProps = state=>{
 return:{
 r1:r1
}
}

然后反应会对状态的任何变化做出反应。如果更改了r1的状态,那么它将更新该组件。


Your question how it update store by returning state. Your reducer will get store(state) and function as input and change the store according to function and return the state to store.
Then we can connect our component to that store to catch any change in it.

正如我们在图像中看到的那样。 Dispatch将改变商店的状态。然后您可以导入(连接)该reducer以查看组件中的更改。(此处TodoItem是该组件)


2
投票

Redux商店只是一个包含应用程序所有状态的对象。 reducer是更新商店的唯一方法。

reducer是一个纯函数,它采用旧状态并返回一个新状态。在reducer中我们需要做的是我们只提供当前存储的旧状态,然后是我们要改变状态的新状态。您可以参考this获取reduce函数的详细说明。

简单来说,reducer使用现有的状态对象更新一些通过reducer函数传递的属性并返回新的对象状态。

以下链接有更好的解释。这是非常好的博客如何创建自己的redux。您将获得redux商店中发生的确切情况。

https://www.jamasoftware.com/blog/lets-write-redux/


0
投票

实际上这是我失去的关于减速器的部分,我没有抓到的部分是减速器输出必须分配给商店物业

let Action={type:'SET_VISIBILITY_FILTER',text: 'test pay load'}

//Invoking Reducer
let store=todoApp({},Action)

//Reducer
function todoApp(state = initialState, action) {
  switch (action.type) {
    case SET_VISIBILITY_FILTER:
      return Object.assign({}, state, {
        message: action.text
      })
    default:
      return state
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.