也許這個問題有點令人困惑,因為我很困惑。我在資料庫中列出了類別的問題我提取了它并創建了一個帖子。現在我正在嘗試編輯帖子。類別為復選框格式,如果選中它會添加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;
uj5u.com熱心網友回復:
我認為問題出在useEffect方法上,因為console.log(categories)它不斷重繪 狀態并且不允許您添加或洗掉專案。首先從中洗掉console.log(categories)和categories依賴項,useEffect并使用 thissetCategories([...categories, cate.name]);而不是 this setCategories([categories.push(cate.name)]);。你不應該categories直接改變
uj5u.com熱心網友回復:
你不應該categories直接改變。所以,而不是
setCategories([categories.push(cate.name)]);
嘗試
setCategories([...categories, cate.name]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/365832.html
標籤:javascript 数组 反应
