不可变变量和纯函数更新状态

Immutable variable and pure function updating state

我正在学习不变性和纯函数。作为新手,我很纠结,我不明白下面的代码是否会改变状态或数据。

这是代码

let state = [];

const updateState = (state, data) => {
  return [...state, data];
}

state = updateState(state, 1);


console.log(state);

我想使用接收状态和数据并更新原始状态的纯函数。

这一行 state = updateState(state, 1); 对我来说感觉像是一个突变,但我不确定。我在改变状态吗?

感谢您的帮助。我正在努力学习。

是的,您的代码突变状态与您认为的完全一致。 updateState 是一个纯函数,因为它不执行任何副作用,不改变任何东西,并且在给定相同输入的情况下将始终具有相同的 return 值,但重新分配 state 是一个改变。这也是像 Redux 这样的库在幕后所做的,例如 here. Note that the important thing is that the current state isn't being mutated in place, it's being completely reassigned to the value of the new state as computed by a pure function. JS isn't a great language for purity and immutability, but if your whole app was just composed of functions and immutable data (with some IO at the edges), it would be possible to never need to reassign or mutate anything (see also this question and the top answer).