【问题标题】:Can't remove the value and uncheck the item of checkbox?无法删除值并取消选中复选框项目?
【发布时间】:2021-11-25 06:58:11
【问题描述】:

也许这个问题有点令人困惑,因为我很困惑。问题我在数据库中列出了我提取的类别并创建了一个帖子。现在我正在尝试编辑帖子。如果选中它会添加setCategories 状态,则类别为复选框格式,如果取消选中它将从状态中删除。我已获取该特定帖子的帖子并保存了类别。我已经向他们展示了检查。现在我正在尝试更改我添加的类别。我成功添加了更多内容,但无法将其删除,也无法取消选中该复选框。请检查此代码...

我用破折号突出显示了 onChange 部分

这里是代码

    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 [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;
    
      useEffect(() => {
        if (!userInfo) {
          history.push('/login');
        }
    
        if (!post || post._id !== postId) {
          dispatch(listPostDetails(postId));
        } else {
          setCategories(post.categories);
          console.log(categories);
        }
        dispatch(listCategory());
      }, [dispatch, history, userInfo, post, postId, categories]);
    
      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.push(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;

【问题讨论】:

  • cat in categories?.filter((cat) =&gt; cat !== cate.name) 应该是 cate?
  • @syltai cate 名称会冲突 我已经使用过cate 将映射categoryList

标签: javascript arrays reactjs


【解决方案1】:

我认为问题出在useEffect 方法上,您是console.log(categories),它不断刷新状态,不允许您添加或删除项目。首先从useEffect 中删除console.log(categories)categories 依赖项,并使用这个setCategories([...categories, cate.name]); 而不是这个setCategories([categories.push(cate.name)]);。你不应该直接更改categories

【讨论】:

    【解决方案2】:

    您不应该直接更改categories。所以,而不是

    setCategories([categories.push(cate.name)]);
    

    试试

    setCategories([...categories, cate.name]);
    

    【讨论】:

    • 我之前使用的那个向我展示了,但如果添加推送一个工作正常但删除一个问题,它就不起作用了。我不能再删除类别了。此行在我创建时适用于我,但这些行不适用于编辑setCategories([...categories, cate.name]);
    • 这就是为什么使用推送方法允许我添加更多但过滤方法不能让我删除是否有任何其他方法可以删除
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    相关资源
    最近更新 更多