【问题标题】:why all toggle switch work at a same time?为什么所有拨动开关同时工作?
【发布时间】:2022-01-25 18:38:29
【问题描述】:

** 我希望我的拨动开关值将数据存储在本地存储中,并且它可以一一工作。我的拨动开关值存储在本地存储中,但是当我想“打开”拨动开关时,我的所有拨动开关同时“打开”。在标签中使用 checked={value} 后,我遇到了这个问题。请帮我解决这个问题。对不起我的低标签英语**

/* eslint-disable array-callback-return */
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import EditIcon from '@mui/icons-material/Edit';
import { Link } from 'react-router-dom';
import { Switch } from '@material-ui/core';
import myConfig from "../../configs/config";

const ShowPopupImage = (props) => {
    const [popupimage, setPopupImage] = useState([]);
    const [searchTerm, setSearchTerm] = useState(...props.name)

    useEffect(() => {
        const POPUP_IMAGE_URL = `${myConfig.API_URL}/popup-image/`;
        const getPopupImage = async () => {
            const response = await axios.get(POPUP_IMAGE_URL, {
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('access-token'),
                    'Content-Type': 'application/json',
                    'accept': 'application/json'
                }
            });
            setPopupImage(response.data);
            console.log(response.data);
        }
        getPopupImage();
    }, []);
    useEffect(()=>{
        setSearchTerm(props.name)
    },[props.name])

    // Toggle Switch value update in Backend
    const [value, setValue] = useState([true]);

    const getValue = (e) => {
        console.log(e.target.checked);
        console.log(e.target.value);

        const id = e.target.value;

        const loadpopupimage = async () => {
            const POPUP_UPDATE_URL = `${myConfig.API_URL}/popup-image/${id}/`;

            value ? setValue(false) : setValue(true);
          
            let formData = new FormData();
            formData.append('is_active',value ? "0" : "1");

            const editPopup = async () => {
                await axios({
                    method: "PUT",
                    url: POPUP_UPDATE_URL,
                    data: formData,
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('access-token'),
                        'Content-Type': 'application/json',
                        'accept': 'application/json'
                    }
                }).then((response) => {
                    console.log(response.data);
                });
            }
            editPopup();
        }

        loadpopupimage();
    }
    // Toggle Switch value store in localstorage
    useEffect(()=>{
        const switchValue = localStorage.getItem("store-forever");
        console.log(switchValue)
        setValue(JSON.parse(switchValue))
    },[]);
    useEffect(()=>{
        localStorage.setItem("store-forever",JSON.stringify(value));
    },[value]);

    return (
        <div className="show_table">
            <table>
                <thead>
                    <tr>
                        <th>No.</th>
                        <th>PopUp Image</th>
                        <th>Title (English)</th>
                        <th>Title (Bangla)</th>
                        <th>Description (English)</th>
                        <th>Description (Bangla)</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody >
                    {
                        popupimage.filter((val) => {
                            return (val.title_en.toLowerCase().includes(searchTerm.toLowerCase()))
                        }).map((popupitem, index) => (
                            <tr key={index} className="t_body_row">
                                <td>{index + 1}</td>
                                <td><img src={popupitem.image} alt=" " className="list_image" /></td>
                                <td>{popupitem.title_en}</td>
                                <td>{popupitem.title_bn}</td>
                                <td>{popupitem.description_en}</td>
                                <td>{popupitem.description_bn}</td>
                                <td>
                                    <Link to={`/popup-image/${popupitem.id}/edit`}><EditIcon /></Link>
                                    <Switch
                                        color="primary"
                                        onChange={ e => getValue(e.target.value)}
                                        value={popupitem.id}
                                        checked={value}
                                        name="checkedB"
                                        inputProps={{ 'aria-label': 'primary checkbox' }}
                                    />
                                </td>
                            </tr>
                        )
                        )
                    }
                </tbody>
            </table>
        </div>
    )
}

export default ShowPopupImage;

【问题讨论】:

    标签: javascript reactjs toggle toggleswitch


    【解决方案1】:

    您对所有项目使用相同的值:

    .map((popupitem, index) => (
        <Switch
            checked={ value }
        />
        ...
    )
    

    您需要为每个项目使用不同的值,例如像

    checked={ value[ (some integer related to the item) ] }
    

    最简单的修复(即使我不推荐它,因为它可能会导致以后的错误)可能是:

    checked={ value[ index ] }
    

    【讨论】:

    • 它不工作。我尝试了多种方法,但没有成功...如果您知道另一种方法,请与我分享
    猜你喜欢
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2013-07-15
    • 1970-01-01
    相关资源
    最近更新 更多