[譯]從零開始Redux(二)不可變性

前言

上一篇,在構(gòu)建了一個簡單地Redux應(yīng)用之后,我們再來討論如何在狀態(tài)轉(zhuǎn)移的過程中保證對象的不可變性。

不可變性

不可變性保證了純函數(shù)無副作用,能夠直觀的邏輯推導(dǎo)。因此Redux本身的原則也保證了狀態(tài)對象的不可變性。因此這篇文章就需要探討如何保證狀態(tài)對象的不可變性

數(shù)組的不可變性

對于數(shù)組的添加,下意識的反應(yīng)肯定是這樣:

const addCounter = (list) => {
  list.push(0);
  return list;
}

這個函數(shù)的問題就是在于破壞了原本list入?yún)⒌牟豢勺冃裕虼宋覀冃枰柚鷍s本身的concat函數(shù)或者...擴(kuò)展操作符:

const addCounter = (list) => {
  return list.concat([0])
  // return [...list, 0]
}

同樣的,我們數(shù)組中移除一個對象應(yīng)該這樣:

  const removeCounter = (list, index) => {
    return list.slice(0, index)
                .concat(list.slice(index + 1))
    // return [...list.slice(0, index), ...list.slice(index+1)]
  }

如果我們需要修改數(shù)組中的一個元素:

  const incrementCounter = (list, index) => {
    return list.slice(0, index)
                .concat([list[index] + 1])
                .concat(list.slice(index + 1));
    // return [...list.slice(0, index), list[index] + 1, ...list.slice(index + 1)];
  }

對象的不可變性

對象的不可變性就比較簡單了。需要使用到是Object對象的assign方法,例如我們做了一個todo List的應(yīng)用,通過點擊勾選待辦事項是否已經(jīng)完成。

  const toggleTodo = (todo) => {
    return Object.assign({}, todo, {
      completed: !todo.completed
    })
  }

assign方法的第一個參數(shù)是一個目標(biāo)對象,后面的參數(shù)按照從左到右的順序依次把自己的所有屬性拷貝到目標(biāo)對象上,如果出現(xiàn)重名則按照先后順序覆蓋掉就行了。這樣相當(dāng)于每次狀態(tài)轉(zhuǎn)移我們都完成了一次重新創(chuàng)建對象并拷貝屬性,還在這個新對象上修改數(shù)據(jù),做到了原數(shù)據(jù)的不可變性。
還有一種做法是使用...擴(kuò)展操作符,不過ES6并不支持,不過在ES7里已經(jīng)有了提案:

  const toggleTodo = (todo) => {
    return {
      ...todo,
      completed: !todo.completed
    }
  }

實戰(zhàn)

我們以一個簡單的待辦事項app為例,這個app支持待辦事項的增加和點擊確認(rèn)完成,首先我們先完成reducer的編碼:

const reducer = (state = [], action) => {
    console.log('enter :' + action);
    switch(action.type){
        case 'ADD_TODO':
            return [...state, 
                {
                    id: action.id,
                    text: action.text,
                    completed:false
                }];
        case 'TOGGLE_TODO':
            let index = action.index;
            return state.map(todo=>{
                if(todo.id == action.id){
                    return Object.assign({}, todo, {completed: !todo.completed})
                }else {
                    return todo;
                }
            })
        default:
            return state;
    }
}

export default reducer;

然后就是展示組件:

class Todo extends Component {
  constructor(props) {
    super(props);
    this.state = {
        text:''
    }
    console.log(props.todoList.length);
  }
  handleChange(event) {
      this.setState({text: event.target.value})
  }

  render() {
    return (
      <div>
        <input type="text" value={this.state.text} onChange={(e)=>this.handleChange(e)}></input>
        <div>
          <button onClick={() => this.props.doAdd(this.state.text)}>+</button>
        </div>
        <ul>
            {this.props.todoList.map(todo => 
                <li 
                  style={todo.completed?{textDecoration:'line-through'}:{}} 
                  key={todo.id} 
                  onClick={()=>this.props.doToggle(todo.id)}>
                  {todo.text}
                </li>
            )}
        </ul>
      </div>
    );
  }
}

export default Todo;

我們看到所有涉及狀態(tài)變化的操作都是通過組件屬性傳入,我們接著看最外層基本頁面:

let store = createStore(reducerTodo);
let idnum = 1;
const render = () => 
    ReactDOM.render(<Todo todoList={store.getState()} 
        doAdd={(input) => {store.dispatch({type: 'ADD_TODO', id: idnum++, text:input})}}
        doToggle={(input) => {store.dispatch({type: 'TOGGLE_TODO', id:input})}}
    />, document.getElementById('root'));
store.subscribe(()=> render());
render();

我們看到傳入的增加待辦事項和勾選的操作就是向Redux狀態(tài)對象下發(fā)對應(yīng)的行為來修改狀態(tài),完成我們的邏輯流轉(zhuǎn),最終我們運行一下:


運行效果
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容