reducer更新但是view没有立即更新

  • 问题:reducer里的state确定有更新,但是view没有立即更新,如果点击页面其他按钮后view才更新

  • 需求:想用react实现一个列表删除记录功能。

  • 思路:列表数据存储在redux中,每条记录后面有个删除按钮,点击获取当前记录,从props中copy列表数组,删除当前记录,将数组传递到action中并触发,reducer更新state,列表view更新。

//container,点击删除执行的方法
handleDelCollection(index){
    let newcol = this.props.collections;
    newcol.splice(index,1);    
    this.props.dispatch(delCollection(newcol));//如果newcol是手动写死的数据,view会立即更新
  }
//action
export function delCollection(collections){
    console.log(collections);
    return {type:'DEL_COLLECTION', collections: collections}
}
//reducer
function collection(state=initialData,action){
  switch( action.type ){
    case 'DEL_COLLECTION':
      console.log(action.collections);  //此处能输出更新后的数据
      return Object.assign({}, state, {
        collections: action.collections
      });
    default : return state;
  }
}

图片描述

阅读 6.8k
2 个回答

个人推测, 问题出现在这两句代码.

let newcol = this.props.collections;
newcol.splice(index,1);    

splice 是会修改原始数组的, 这样相当于直接对 state 中的数据直接修改.

React Redux 会在 shouldComponentUpdate 中对新的 props 进行浅层的判等检查,以期提升性能。如果所有的引用都是相同的,则返回 false 从而跳过此次对组件的更新。

建议用 filter 之类会返回新数组的方法改写试试

http://cn.redux.js.org/docs/f...

既然用了redux就很容易解决了,

// 暂定 getList 是你获取列表的接口
// deleteItem 是删除的接口

// action

export const deleteListItem = (dispatch, id) => {
    return dispatch => {
        // 使用 deleteItem接口 删除 id 这条数据
        .then(function (res) {
            if(res.data.status === 200) {
                dispatch(getList()) // 重新获取一次数据就行了
            }
        })
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题