简体   繁体   English

无法删除值并取消选中复选框项目?

[英]Can't remove the value and uncheck the item of checkbox?

Maybe the question is a little bit confusing because I'm confused.也许这个问题有点令人困惑,因为我很困惑。 The problem I have listed categories in the database I fetched it and create a post.问题我在数据库中列出了我提取的类别并创建了一个帖子。 Now I'm trying to edit the post.现在我正在尝试编辑帖子。 The categories are in checkbox format if check it adds the setCategories state if uncheck it will remove from the state.如果选中它会添加setCategories state,则类别为复选框格式,如果取消选中它将从 state 中删除。 I have fetched the post and saved categories for that particular post.我已获取该特定帖子的帖子并保存了类别。 I've shown them checked.我已经向他们展示了检查。 Now I'm trying to change the categories I've added.现在我正在尝试更改我添加的类别。 I'm successful to add more but cannot remove it as well am unable to uncheck the checkbox.我成功添加了更多内容,但无法将其删除,也无法取消选中该复选框。 Please check this code...请检查此代码...

I'm highlighted the onChange part with dashes我用破折号突出显示了 onChange 部分

here is code这是代码

    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;

I think the problem is on useEffect method you are console.log(categories) it keeps on refreshing the state and not allowing you to add or remove items.我认为问题出在useEffect方法上,您是console.log(categories)它不断刷新 state 并且不允许您添加或删除项目。 first remove the console.log(categories) and also categories dependencies from useEffect and use this setCategories([...categories, cate.name]);首先从useEffect中删除console.log(categories)以及categories依赖项并使用此setCategories([...categories, cate.name]); instead of this setCategories([categories.push(cate.name)]);而不是这个setCategories([categories.push(cate.name)]); . . You shouldn't change categories directly您不应该直接更改categories

You shouldn't change categories directly.您不应该直接更改categories So, instead of所以,而不是

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

try尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM