有人向我解释为什么我们从不直接在Redux中写状态?

有人向我解释为什么我们从不直接在Redux中写状态?

问题描述:

我真的对Redux中使用的Object.assign()感到困惑.

I was really confused with Object.assign() used to in redux.

我不明白下面的代码为什么起作用.

I don't understand why does the below code working..

import { createStore } from "redux"

const userReducer = function (state={}, action) {
  switch (action.type) {
    case "CHANGE_USER_NAME":
      state.name = action.payload
      break;
    case "CHANGE_USER_AGE":
      state.age = action.payload
      break;
    default:
  }
  return state;
}

const store = createStore(userReducer)

store.subscribe(() => console.log(store.getState()))

store.dispatch({ type: "CHANGE_USER_NAME", payload: "paul" })
store.dispatch({ type: "CHANGE_USER_AGE", payload: 74 }) // It returned { name: "paul", age: 74 }
store.dispatch({ type: "CHANGE_USER_NAME", payload: "john" }) // It returned { name: "john", age: 74 } changed name to "john" but age is same. This point. is not immutable object?

我只是直接写状态值,但结果是我期望的值...

I just write directly to state's value, but the result is the value I expected...

user.name已更改,但user.age未更改.

对我来说,这似乎是一个不变的对象.我错了吗?

It looks like an immutable object to me. Am I wrong ?

有人向我解释为什么我们从不直接写状态书? 对不起我的假问题.我在尝试原因,但我不知道为什么.

Somebody explain to me why we never write directly to state ? Sorry about my dummy question. I was trying reason but I don't know why..

要理解为什么我们总是要返回一个新对象,您必须了解函数式编程中的纯函数和副作用.

To understand why we want to always return a new object, you have to understand pure functions and side effects in functional programming.

纯函数将参数作为其输入数据,并将 return 数据作为其输出.这使我们不必更改输入,而是从输入中产生新数据.

Pure functions take arguments as their input data and return data or functions as their output. This allows us to not mutate the input, but instead produce new data off of the input.

这样,原始状态将保持不变,而是由全新的状态对象替换,从而使函数保持纯净,不会产生副作用.

In this way the original state will remain unchanged, and instead will be replaced by an entirely new state object, keeping your function pure, not producing side effects.