【问题标题】:reactjs: after action redux not re-renderreactjs:动作后redux不会重新渲染
【发布时间】:2017-06-04 15:57:51
【问题描述】:

我有一个问题,关于更新 redux 中的状态,我有这段代码列出了一些元素并且效果很好,现在当我删除其中一个元素时也可以工作,但是在删除点击后列表没有更新,我必须重新加载页面,才能看到更改,一些指南

// 组件列表component.js

export default class listcomponent extends Component {
    constructor(props) {
    super(props);
  }
  render() {
    return(
      <div>
        {this.renderGroup()}
      </div>
    )
  }
   renderGroup(){
    return this.props.allList.map((item, index)=>{
      return(
          <div className="panel panel-success tour-item-list">
              <h3 className="panel-title">{item.name} </h3>
              <div onClick={()=>this.handleDelete(item.key)}>delete</div>
        </div>  
      )
    })
  }
  handleDelete(key){
      this.props.deleteGroup(key, function(err,res){
        if(err){
          console.log(err)
        }else{
          console.log(res);

        }
      })
    }
  }

//container -->将listcomponent.js加入action

import {getListGroup} from './action/listGroup.js';
import {deleteGroup} from './action/deleteGroup.js';
import listcomponent from './listcomponent.jsx'
class ListContainer extends Component{
  componentDidMount(){
      this.props.getListGroup();
      this.props.deleteGroup();
    } 
    render (){
        return (
                <listcomponent allList={this.props.allList} deleteGroup={this.props.deleteGroup} />
        );
    }
}

function mapStateToProps(store) {
  return {
    allList: store.allList
  };
}

function matchDispatchToProps(dispatch) {
  return bindActionCreators({
    getListGroup: getListGroup,
    deleteGroup: deleteGroup
  }, dispatch);
}

export default connect(mapStateToProps, matchDispatchToProps)(ListContainer); 

//reducer ---> listReducer.js

export const listReducer = (state=[], action)=>{
  switch(action.type){
    case 'GET_GROUP_REQUEST':
      return state;
    case 'GET_GROUP_FAILURE':
      return state;
    case 'GET_GROUP_SUCCESS':
      return [...state, action.payload];
    case 'DELETE_GROUP_SUCCESS':    
        const idToDelete = action.payload;
          return state.filter((item) => {
             item.tour_groups[0].tour_group_key !== idToDelete
         });
    default:
      return state;     
  }
}

// 通用reducer --> reducer.js

 export default import { listReducer } from './listReducer.js'

    const reducers = combineReducers({
      allGroup:listGroupReducer

})

// 存储 --> store.js

import reducers from './reducer.js';

const store = createStore(
  reducers, 
   applyMiddleware(thunk,  logger())
)

//要编辑的服务--getlistgroup.js

export const deleteGroup = (tour_group_key, callback)=>{    
    return function(dispatch){
        dispatch({type:'DELETE_GROUP_REQUEST'});
        axios.delete('x/v1/user/tour_groups/'+tour_group_key)
        .then((response)=>{
            dispatch({type:'DELETE_GROUP_SUCCESS', payload:tour_group_key});
            if (typeof callback === 'function') {
                callback(null, response.data);
            }
        })
        .catch((response)=>{
            dispatch({type:'DELETE_GROUP_FAILURE'})
            if(typeof callback ==='function'){
                callback(response.data, null)
            }   
        })
    } 
} 

// 服务列表 -->listgroup.js

export const getListGroup = (callback)=>{
        return function(dispatch){
            dispatch({type:'GET_GROUP_REQUEST'});
            axios.get('x/v1/user/tour_groups')
            .then((response)=>{
                dispatch({type:'GET_GROUP_SUCCESS', payload:response.data});
                if (typeof callback === 'function') {
                    callback(null, response.data);
                }
            })
            .catch((response)=>{
                dispatch({type:'GET_GROUP_FAILURE'})
                if(typeof callback ==='function'){
                    callback(error.response.data, null)
                }   
            })
        } 
    } 

// 我调用的服务

{
  "status": "SUCCESS",
  "count": 2,
  "tour_groups": [
    {
      "tour_guide": "ahpkZXZ-c3RyZWV0dG91ci1kZXZlbG9wbWVudHIRCxIEVXNlchiAgICAgICACQw",
      "description": "asfease",
      "name": "fefe",
      "tour_group_key": "ahpkZXZ-c3RyZWV0dG91ci1kZXZlbG9wbWVudHInCxIEVXNlchiAgICAgICACQwLEglUb3VyR3JvdXAYgICAgIDwuwkM"
    },
    {
      "tour_guide": "ahpkZXZ-c3RyZWV0dG91ci1kZXZlbG9wbWVudHIRCxIEVXNlchiAgICAgICACQw",
      "description": "ente",
      "name": "pariente",
      "tour_group_key": "ahpkZXZ-c3RyZWV0dG91ci1kZXZlbG9wbWVudHInCxIEVXNlchiAgICAgICACQwLEglUb3VyR3JvdXAYgICAgIDwuwgM"
    }
  ]
}

【问题讨论】:

  • 您是否向您的操作创建者发送操作以删除该项目?例如。你有处理 DELETE_ITEM 等类型的 reducer 吗?
  • 嗨,感谢您的帮助,是的,我有删除操作:export const deleteGroup = (data, callback)=>{ return function(dispatch){ dispatch({type:'DELETE_GROUP_REQUEST'} ); axios.delete('x/v1/user/tour_groups/'+data) .then((response)=>{ dispatch({type:'DELETE_GROUP_SUCCESS', payload:response.data}); if (typeof callback === 'function') { callback(null, response.data); } }) .catch((response)=>{ dispatch({type:'DELETE_GROUP_FAILURE'}) }) } }
  • 你能告诉我你在哪里处理 DELETE_GROUP_SUCCESS 吗?
  • 在减速器中?
  • 是的,在减速机中

标签: javascript reactjs redux react-redux axios


【解决方案1】:

您必须在 reducer 中处理 DELETE 操作,否则 redux 不知道您的状态已更新。换句话说:

你的减速器

export const listReducer = (state=[], action)=>{
  switch(action.type){
    case 'GET_GROUP_REQUEST':
      return state;
    case 'GET_GROUP_FAILURE':
      return state;
    case 'GET_GROUP_SUCCESS':
      return [...state, action.payload];
    case 'DELETE_GROUP_SUCCESS':
      const idToDelete = action.payload;
      return state.filter((item) => {
          item.id !== idToDelete
      });
    default:
      return state;     
  }
}

您的动作创建者:

export const deleteGroup = (id, callback)=>{  
    return function(dispatch){
        dispatch({type:'DELETE_GROUP_REQUEST'});
        axios.delete('x/v1/user/tour_groups/'+id)
        .then((response)=>{
            dispatch({type:'DELETE_GROUP_SUCCESS', payload: id});
        })
        .catch((response)=>{
            dispatch({type:'DELETE_GROUP_FAILURE'})
        })
    } 
} 

请注意,reducer 中的 'id' 必须与状态数组中对象的键匹配。因此,如果您的数组中的项目如下所示:

[ {
    user_id: '12',
    profile: {...}
  },
  ...
]

您必须确保使用:

return state.filter((item) => {
    item.user_id !== idToDelete
});

如果您的项目只是一个扁平的字符串数组,那么我建议您重构您的状态的外观。另外,我不熟悉将回调传递给您的动作创建者,但我几乎可以肯定这不是好的做法。

编辑:根据您的代码,您的 DELETE_GROUP_SUCCESS 案例是错误的。 *注意:这假设您有一个 combineReducers 调用。

case 'DELETE_GROUP_SUCCESS':    
    const idToDelete = action.payload;
    return state.filter((tourGroup) => {
        tourGroup.tour_group_key !== idToDelete
    });

【讨论】:

  • 嗨,我改变了 mi reducer,但是当重新渲染时,将所有项目删除到列表中
  • 您可以将动作创建者添加到您的原始问题中吗?我需要查看 deleteGroup() 的内容
  • 好的,我更新了我的答案,希望对您有所帮助,否则您需要向我发送一个示例 repo,我可以帮助您解决问题
  • 嗨,列表不起作用删除所有项目,我用 json 更新,我做了你发给我的更改,你能检查一下
  • 很难说出你的状态实际上是什么样的,但根据我所看到的,你的函数只处理你状态的 "tour_groups": [] 部分,因为它是基于数组的,如果那是你唯一没有正确处理状态的减速器。
猜你喜欢
  • 2020-09-26
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2016-09-09
  • 2021-12-06
相关资源
最近更新 更多