问:1.由于reducer强调了不可变数据的概念,为什么不在深拷贝之后返回状态,例如_ .cloneDeep
2.由于无法直接更改状态,所以为什么不使用Object.freeze或类似的东西使状态不变
import { SET_BOOKS, ADD_BOOK, REMOVE_BOOK, CHANGE_BOOK_PRICE } from '../actions/book.js'
const initBooks = []
const books = (state, action) => {
if (state === undefined) {
state = initBooks
}
//Or better performance_ .cloneDeep
let tmpBooks = JSON.parse(JSON.stringify(state))
switch (action.type) {
case SET_BOOKS:
return action.books
break
case ADD_BOOK:
// return [...state,action.newBook]
tmpBooks.push(action.newBook)
return tmpBooks
break
case REMOVE_BOOK:
return state.filter(item => {
return item.id !== action.bookId
})
break
case CHANGE_BOOK_PRICE:
tmpBooks.forEach(item => {
if(item.id===action.bookId){
item.price=action.newPrice
}
});
return action.books
break
default:
return state
}
}
export default books
答:我不知道我的想法与您的想法不同。您可以看一下Combinereducers的源代码:
var hasChanged = false
var nextState = {}
for (var i = 0; i < finalReducerKeys.length; i++) {
var key = finalReducerKeys[i]
var reducer = finalReducers[key]
var previousStateForKey = state[key]
var nextStateForKey = reducer(previousStateForKey, action)
if (typeof nextStateForKey === 'undefined') {
var errorMessage = getUndefinedStateErrorMessage(key, action)
throw new Error(errorMessage)
}
nextState[key] = nextStateForKey
hasChanged = hasChanged || nextStateForKey !== previousStateForKey
}
return hasChanged ? nextState : state
关键是,reduce每次返回新状态时,都会将其与旧状态进行比较= = =如果false认为存储已更改,则触发页面重绘;如果为true,则将其视为不变,并且不会触发重绘。因此,reducer返回新状态,以通知Redux到Redux重绘页面。