我見過很多例子,比如const store = createStore(someReducer)當我們希望通過 reducer 改變它時,讓它成為一個常量有什么用?為什么不是 var?
uj5u.com熱心網友回復:
商店的內容會改變,但你永遠不會將它重新分配給另一個商店,因此const.
通常,現在最好使用letand const,因為這些范圍與var. var不僅限于塊范圍,因此變數會以意想不到的方式相互覆寫。考慮這兩個代碼片段:(來自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(or 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
uj5u.com熱心網友回復:
的值store永遠不會更改為指向新商店。商店的狀態發生了變化,但store始終只指創建的一個商店。您可以在檔案createStore的示例中看到:
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永遠不會在那里獲得新值,但它所參考的商店的狀態會發生變化。請注意最后獲取商店當前狀態的位。
讓我們通過在getState 之前添加呼叫來更清楚地說明dispatch:
顯示代碼片段
// 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永遠不會改變。
uj5u.com熱心網友回復:
const不會創建不可變的資料結構,它只是防止該變數被重新分配。
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 store 物件就是一個很好的例子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/442493.html
標籤:javascript 还原 反应还原 还原商店
上一篇:有沒有辦法節省JS物件的鍵空間?
