不可变状态不刷新

时间:2019-02-19 11:13:33

标签: redux react-redux

我正在制作一个React应用,我有一个“类别”集合和一个带有删除类别按钮的表示层。如果我重新加载页面,则我的redux状态刷新将持续存在。我不明白为什么它不起作用,因为对我而言似乎是不变的,再加上我在另一个组件中使用相同的模式并且工作正常。我想念什么?

这是减速器:

import {DELETE_CATEGORY} from './../../actionType';
const initialState = {
  singleCategory: {},
  categories: []
}

export default function(state = initialState, action){
  switch(action.type){
    case DELETE_CATEGORY:
    return {
      ...state,
      categories: state.categories.filter (category=>category._id !== category.payload)
    }

    default:
      return state;
  }
}

顺便说一句,如果我刷新页面,商店将被正确过滤。 这是我的动作:

// Delete Category by id
export const deleteCategory = (categoryId) => dispatch => {
  console.log('disp');
  axios
    .delete(`/api/categories/${categoryId}`)
    .then( success => {
      dispatch(successMessage);
      return dispatch({
        type: DELETE_CATEGORY,
        payload: categoryId
      })
    })
    .catch(err =>
      dispatch({
        type: GET_ERRORS,
        payload: err.response.data
      }),
    );
};

这是我的组成部分:

class ShowCategoriesPage extends Component {

  componentDidMount(){
    this.props.getCategories()
  }
  handleDeleteCategory = (categoryId) => {
    this.props.deleteCategory(categoryId);
  }
  render() {
    const { categories } = this.props.categories;
    return (
      <SidebarLayout>
        {categories.map(category => (
          <CategoryCard
            name={category.name}
            type={category.type}
            id={category._id}
            handleDeleteCategory={this.handleDeleteCategory}
          />
        ))}
        <Button variant="contained" color="primary" style={{marginTop: '36px'}} >
        ADD NEW CATEGORY
      </Button>
      </SidebarLayout>
    )
  }
}

这是组件:

const SimpleCard = ({ classes, name, type, id, deleteCategory })=>{

  const onDeleteCategory = (categoryId) => {
    deleteCategory(categoryId);
  }

  return (
    <Card className={classes.card}>
      <CardContent>
        <Typography variant="h5" component="h2">
          {name}
        </Typography>
        <Typography className={classes.pos} color="textSecondary">
          {type}
        </Typography>
        <Button variant="small" color="primary" style={{marginTop: '36px'}} onClick={()=>onDeleteCategory(id)}>
        REMOVE
      </Button>
        <Button variant="small" color="primary" style={{marginTop: '36px'}} >
        EDIT
      </Button>
      </CardContent>
    </Card>
  );
}

我阅读了redux的官方文档,它建议像我一样使用拼接或过滤器,您能理解为什么单击删除按钮后redux状态没有刷新吗?

我要避免强制刷新状态。

1 个答案:

答案 0 :(得分:2)

您确定这行是正确的

      categories: state.categories.filter (category=>category._id !== category.payload)

而不是

      categories: state.categories.filter (category=>category._id !== action.payload)