You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React编辑文章时分类复选框无法取消勾选、无法删除已选分类值求助

问题原因

一共有3处错误导致当前异常:

  1. 勾选分类时的状态更新逻辑错误
    Array.push()方法的返回值是新增元素后的数组长度,不是修改后的数组本身。你写的setCategories([categories.push(cate.name)])会直接把分类状态从原本的字符串数组,改成只有一个数字元素的数组,后续取消勾选时filter匹配不到分类名,自然无法删除原有分类、也没法取消勾选。
  2. useEffect依赖项错误
    你把categories加入了useEffect的依赖数组,只要修改分类状态就会触发useEffect重新执行,此时如果post存在就会重新把post.categories赋值给状态,相当于刚修改的分类直接被原有保存的分类覆盖,等于修改无效。
  3. 重置方法的类型错误
    resetHandler里你调用setCategories('')把分类状态设成了空字符串,但该状态初始值是数组,类型不匹配会引发后续逻辑异常。

修正后完整代码

import React, { useEffect, useState } from 'react';
import { Alert, Button, Card, Container, Form } from 'react-bootstrap';
import ReactMarkdown from 'react-markdown';
import { useDispatch, useSelector } from 'react-redux';
import { toast, ToastContainer } from 'react-toastify';
import { listCategory } from '../actions/categoryActions';
import { listPostDetails, updatePost } from '../actions/postActions';

const EditPost = ({ history, match }) => {
  const postId = match.params.id;
  // 补全原代码缺失的其余状态定义
  const [title, setTitle] = useState('');
  const [img, setImg] = useState('');
  const [desc, setDesc] = useState('');
  const [categories, setCategories] = useState([]);

  const dispatch = useDispatch();

  const userLogin = useSelector((state) => state.userLogin);
  const { userInfo } = userLogin;

  const categoryList = useSelector((state) => state.categoryList);
  const { categories: cateList } = categoryList;

  // 补全原代码缺失的post数据取数逻辑
  const postDetails = useSelector((state) => state.postDetails);
  const { post } = postDetails;

  useEffect(() => {
    if (!userInfo) {
      history.push('/login');
    }
    dispatch(listCategory());
    if (!post || post._id !== postId) {
      dispatch(listPostDetails(postId));
    } else {
      // 初始化所有表单字段
      setTitle(post.title);
      setImg(post.img);
      setDesc(post.desc);
      setCategories(post.categories);
    }
    // 移除categories依赖,避免循环触发重置
  }, [dispatch, history, userInfo, post, postId]);

  const resetHandler = () => {
    setTitle('');
    setImg('');
    setCategories([]); // 修正为数组类型,和初始值匹配
    setDesc('');
  };

  const submitHandler = (e) => {
    e.preventDefault();
    dispatch(updatePost(postId, title, desc, img, categories));
    resetHandler();
    history.push('/my_posts');
  };

  return (
    <div className=" createPost mt-4 py-4">
      <ToastContainer />
      <Container>
        <h2>EDIT POST</h2>
        <Form onSubmit={submitHandler}>
          <!-- 可自行补充标题、封面、描述对应的表单项 -->
          <Form.Group controlId="category" className="mb-2">
            <Form.Label>Select Categories</Form.Label>
            <br />
            {cateList?.map((cate) => (
              <Form.Check
                inline
                key={cate._id}
                type="checkbox"
                label={cate.name}
                checked={categories.includes(cate.name)}
                onChange={(e) => {
                  if (e.target.checked) {
                    // 用扩展运算符生成新数组实现新增
                    setCategories([...categories, cate.name]);
                  } else {
                    setCategories(
                      categories?.filter((cat) => cat !== cate.name)
                    );
                  }
                }}
              />
            ))}
          </Form.Group>
          <Button
            type="submit"
            variant="success"
            style={{ letterSpacing: '2px', fontWeight: 'bold' }}>
            UPDATE
          </Button>
        </Form>
      </Container>
    </div>
  );
};

export default EditPost;

内容的提问来源于stack exchange,提问作者Developer Nans

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 11:24:04