繁体   English   中英

刷新后如何保持复选框处于选中状态?

[英]How can I keep the check-boxes checked after refresh?

即使在刷新页面后,我需要在此代码中添加什么才能使复选框保持选中状态? 代码示例或解释将不胜感激这是该项目的完整代码: https://github.com/Orelso/Project-notes

如果您需要我添加代码的任何其他部分,请告诉我

 import React from "react"; import Card from '@mui/material/Card'; import CardHeader from '@mui/material/CardHeader'; import CardContent from '@mui/material/CardContent'; import { FormControlLabel, FormGroup, IconButton, Typography } from "@mui/material"; import { DeleteOutlined } from "@mui/icons-material"; import { makeStyles } from "@mui/styles"; import Checkbox from '@mui/material/Checkbox'; import { createTheme, ThemeProvider } from "@mui/material"; import { blue } from "@mui/material/colors"; const theme = createTheme ({ palette: { category: { color: blue } } }) const useStyles = makeStyles({ test: { border: (note) => { if (note.category == 'HTML/CSS') { return '2px solid blue' } else if (note.category == 'Javascript') { return '2px solid green' } else if (note.category == "Javascript/React") { return '2px solid yellow' }else if (note.category == 'MUI') { return '2px solid red' } } }, }) export default function NoteCard({ note, handleDelete }) { const classes = useStyles(note) return ( <div> <Card elevation={10} className={classes.test}> <CardHeader action={ // 200 <IconButton onClick={() => handleDelete(note.id)}> <DeleteOutlined /> </IconButton> } title={<span style={{fontFamily: "monospace", color: "#000000"}}>{note.title}</span>} subheader={<span style={{fontFamily: "Courier New", color: "#000000"}}>{note.category}</span>} /> <CardContent> <FormGroup> <FormControlLabel sx={{color: '#000000'}} control={<Checkbox color="warning" />} label={note.details} /> <FormControlLabel sx={{color: '#555555'}} control={<Checkbox />} label={note.details2} /> <FormControlLabel sx={{color: '#000000'}} control={<Checkbox />} label={note.details3} /> <FormControlLabel sx={{color: '#555555'}} control={<Checkbox />} label={note.details4} /> </FormGroup> </CardContent> </Card> </div> ) }

您可以使用 redux persist 将数据保存在本地存储中,这是保存数据或从后端从 rest API 获取数据的唯一方法

您可以使用本地存储保存用户输入的数据。

localStorage.setItem("keyname", "valueName");

之后,在您需要获取此已保存数据的组件中,您可以访问存储。

localStorage.getItem("keyname");

因此,在您的情况下,您需要在用户更改某些内容后首先将 setItem 设置为本地存储。 然后更新 state。 使用 useEffect 您可以在每次加载组件时从 localstorage 中获取项目。

var style,classes;
const [mystate,setMystate] = useState();

useEffect(()=>{
    style = localStorage.getItem(keyname);
    classes = setMystate(style);
},[]);

之后,您可以出于您的目的访问此变量。 但是每次用户更改与之相关的内容时,您都需要更新此 state。

如果您在整个应用程序中需要这些复选框的数据,而不仅仅是在一个组件中,那么您需要使用上下文或 redux。 一般来说,您可以访问每个组件中的存储,但通常我们会创建一个全局上下文并访问它以获得全局变量。 例如,应用程序的全局样式或检查用户是否登录。

希望这会有所帮助,问候,

暂无
暂无

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

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