美文网首页
[译]从零开始Redux(二)不可变性

[译]从零开始Redux(二)不可变性

作者: ro9er | 来源:发表于2019-02-11 10:00 被阅读0次

    前言

    上一篇,在构建了一个简单地Redux应用之后,我们再来讨论如何在状态转移的过程中保证对象的不可变性。

    不可变性

    不可变性保证了纯函数无副作用,能够直观的逻辑推导。因此Redux本身的原则也保证了状态对象的不可变性。因此这篇文章就需要探讨如何保证状态对象的不可变性

    数组的不可变性

    对于数组的添加,下意识的反应肯定是这样:

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

    这个函数的问题就是在于破坏了原本list入参的不可变性,因此我们需要借助js本身的concat函数或者...扩展操作符:

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

    同样的,我们数组中移除一个对象应该这样:

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

    如果我们需要修改数组中的一个元素:

      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的应用,通过点击勾选待办事项是否已经完成。

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

    assign方法的第一个参数是一个目标对象,后面的参数按照从左到右的顺序依次把自己的所有属性拷贝到目标对象上,如果出现重名则按照先后顺序覆盖掉就行了。这样相当于每次状态转移我们都完成了一次重新创建对象并拷贝属性,还在这个新对象上修改数据,做到了原数据的不可变性。
    还有一种做法是使用...扩展操作符,不过ES6并不支持,不过在ES7里已经有了提案:

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

    实战

    我们以一个简单的待办事项app为例,这个app支持待办事项的增加和点击确认完成,首先我们先完成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;
    

    我们看到所有涉及状态变化的操作都是通过组件属性传入,我们接着看最外层基本页面:

    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状态对象下发对应的行为来修改状态,完成我们的逻辑流转,最终我们运行一下:


    运行效果

    相关文章

      网友评论

          本文标题:[译]从零开始Redux(二)不可变性

          本文链接:https://www.haomeiwen.com/subject/hgmksqtx.html