为什么 redux 中的 store 应该是一个常量变量?

Why should the store in redux should be a constant variable?

我见过很多例子,比如const store = createStore(someReducer)当我们想通过reducer改变它时,把它设为常量有什么用?为什么不是 var?

商店的内容会发生变化,但您永远不会将其重新分配给其他商店,因此 const

一般来说,现在最好使用 letconst,因为它们的范围不同于 varvar 不限于块范围,因此变量会以意想不到的方式相互覆盖。考虑这两个代码片段:(示例来自 MDN

var x = 1;

if (x === 1) {
  var x = 2; // just changes the value of the outer variable

  console.log(x);
  // expected output: 2
}

console.log(x);
// expected output: 2

如果您改用 let(或 const),变量仅存在于创建它们的范围内 - 相互隐藏,但不覆盖彼此的值:


let x = 1;

if (x === 1) {
  let x = 2; // new variable with the same name for the inner block, shadows the outer variable

  console.log(x);
  // expected output: 2
}

console.log(x);
// expected output: 1

store 的值永远不应更改为指向 商店。商店的 state 发生变化,但 store 始终仅指代创建的一个商店。您可以在 the createStore documentation's example:

中看到
import { createStore } from 'redux'

function todos(state = [], action) {
  switch (action.type) {
    case 'ADD_TODO':
      return state.concat([action.text])
    default:
      return state
  }
}

const store = createStore(todos, ['Use Redux'])

store.dispatch({
  type: 'ADD_TODO',
  text: 'Read the docs'
})

console.log(store.getState())
// [ 'Use Redux', 'Read the docs' ]

store 永远不会在那里获得新值,但它所指的商店的 state 会发生变化。注意末尾获取商店当前状态的位。

让我们通过在 dispatch:

之前添加对 getState 的调用来使这一点更清楚

// console.log(Object.keys(window).sort());
const { createStore } = RTK;

function todos(state = [], action) {
  switch (action.type) {
    case 'ADD_TODO':
      return state.concat([action.text])
    default:
      return state
  }
}

const store = createStore(todos, ['Use Redux'])

console.log("before dispatch:", JSON.stringify(store.getState()))
// before dispatch: ["Use Redux"]

store.dispatch({
  type: 'ADD_TODO',
  text: 'Read the docs'
})

console.log("after dispatch: ", JSON.stringify(store.getState()))
// after dispatch: ["Use Redux", "Read the docs"]
<script src="https://unpkg.com/@reduxjs/toolkit"></script>

商店的状态发生变化,而不是正在使用哪个商店,所以store永远不会改变。

const 不会创建不可变数据结构,它 just prevents that variable from being reassigned.

const numbers = [1,2,3];

// mutating the object assigned to `numbers` is fine
numbers.push(4);

// reassigning the variable is not
numbers = [1,2,3,4];

通常,const 用于不会重新分配变量的地方,以及需要块作用域的地方。 redux 存储对象就是一个很好的例子。