如何解决在ReactJS中处理更新
我正在制作一个应用程序,以使用户能够确定自己的创作是处于活动状态还是非活动状态,而负责该活动的API路由是
(我正在使用NextJs Api路由)
import { NextApiRequest,NextApiResponse } from "next";
import { decryptCookie } from "../../../lib/cookie";
import { prisma } from "../../../lib/prisma";
interface User {
email: string;
issuer: string;
}
export default async (req: NextApiRequest,res: NextApiResponse) => {
if (req.method !== "PUT") return res.status(405).end;
let userFromCookie: User;
try {
userFromCookie = await decryptCookie(req.cookies.auth);
if (!userFromCookie.email) {
throw new Error("Cannot find user. Unable to proceed with creation.");
}
const userEmail = userFromCookie.email;
const active = JSON.parse(req.body);
const userInDb = await prisma.user.findOne({
where: {
email: userEmail,},});
const response = await prisma.brainstorm.update({
data: {
active,where: {
id: userInDb.id,});
res.status(201).json({ response });
} catch (error) {
return res.status(500).end(error.message);
}
};
包含此动作的组件从父组件中的map方法接收作为道具的数据
我将在此处放置整个组件,但是你们可能会担心Switch指示更改的活动性和功能。
import React,{ useState,useEffect } from "react";
import Switch from "react-switch";
import {
Container,BrainstormInfo,BrainstormTitle,Active,Group,StormPieces,} from "./styles";
import { Brainstorm } from "../../pages/user-dashboard";
import useFormatDate from "../../hooks/useFormatDate";
import produce from "immer";
interface Props {
brainstormData: Brainstorm;
}
const UserBrainstormCard: React.FC<Props> = ({ brainstormData }) => {
if (!brainstormData) return <h1>Loading...</h1>;
const [active,setActive] = useState(brainstormData.active);
const formatedDate = useFormatDate(
(brainstormData.createdAt as unkNown) as string
);
async function handleActiveness() {
setActive(!active);
const response = await fetch("/api/brainstorm/update",{
method: "PUT",body: JSON.stringify(active),});
const data = await response.json();
setActive(data.response.active);
}
return (
<Container>
<BrainstormInfo>
<p>Brainstorm</p>
<p>{formatedDate}</p>
</BrainstormInfo>
<BrainstormTitle>
<h3>{brainstormData.title}</h3>
</BrainstormTitle>
<Active>
<Group>
<p>Active:</p>
<Switch
offHandleColor="#eee"
onHandleColor="#eee"
draggable={false}
onChange={handleActiveness}
checked={active}
checkedIcon={false}
uncheckedIcon={false}
height={15}
width={30}
handleDiameter={20}
offColor="#f13030"
onColor="#2dea8f"
/>
</Group>
<StormPieces>
<p>
{brainstormData.stormPieces.length}
{` `}Stormpieces
</p>
</StormPieces>
</Active>
</Container>
);
};
export default UserBrainstormCard;
发生了对API的调用,但是当我更新页面时,一切都回到了最初的值。
我非常确定问题与状态有关,并且我应该找到一种在状态中插入此值的方法。但是我不知道如何做到这一点
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。