代码之家  ›  专栏  ›  技术社区  ›  Ankit Kumar

如何在提交数据时重新加载卡?

  •  0
  • Ankit Kumar  · 技术社区  · 2 年前

    我想在提交卡片数据时显示卡片。但我必须刷新页面才能看到我想在提交数据时自动刷新卡组件的更改。 我已经使用了使用效果,但仍然不起作用。值变为true,但不显示数据。尽管如此,我还是要刷新页面。我该如何解决这个问题?

    enter image description here

    import { TextField, Box, Typography, Button, Link, DialogContent, CircularProgress, Dialog, DialogTitle, DialogContentText, DialogActions } from '@mui/material';
    import React, { useEffect } from 'react';
    import Cards from 'react-credit-cards';
    import 'react-credit-cards/es/styles-compiled.css';
    import { useContext, useState } from "react";
    import { CardData } from '../../services/user-controller';
    import { StatusCodes } from 'http-status-codes';
    import { addCard, cardDelete, getCardList } from '../../services/card-controller';
    import { ApplicationContext } from '../../context/applicationCtx';
    import { nanoid } from 'nanoid';
    import CancelIcon from '@mui/icons-material/Cancel';
    import styles from "./mystyle.module.css"
    import loadCardList from "../../pages/auth/main-app.js"
    export default function PaymentForm() {
    
      const {
        getCardsList_CTX, setCardList_CTX, getReloadModuleData, setReloadModuleData
      } = useContext(ApplicationContext);
    
      
      const [error, setError] = useState('');
      const [getLoaderState, setLoaderState] = useState(false);
      const [cardClick, setCardClick] = useState(false);
      const [cardNumber, setCardNumber] = useState('');
      const [cardName, setCardName] = useState('');
      const [cardExpiry, setCardExpiry] = useState('');
      const [cardCvv, setCardCvv] = useState('');
      const [focus, setFocus] = useState('');
      const [cardId, setCardId] = useState('');
      // const [inpval, setInpval] = useState('');
      const [cardn, setCardn] = useState('');
      const [carde, setCarde] = useState('');
    
      const [open, setOpen] = useState(false);
      const [deleteCard, setDeleteCard] = useState(null);
      const [reloadData,setReloadData] = useState(false);
    
      const handleClickOpen = (card) => {
        setOpen(true);
        setDeleteCard(card)
      };
    
      const handleClose = () => {
        setOpen(false);
      };
    
      const handleDeleteCard = async function (){
        let cardNum = `000000000000${deleteCard.cardNo.substring(4,8)}`
    
        try {
    
          setLoaderState(true);
    
          let response = await cardDelete({
            "cardNo": cardNum,
            "expiryMonth": deleteCard.expiryMonth,
            "expiryYear": deleteCard.expiryYear
          })
          if(response.status === 200 || response.status === 202 ){
            setLoaderState(false);
            setOpen(false)
            
          }
    
        } catch (err) {
          setLoaderState(false);
          if (err.data) {
    
            //TODO:: ADD ERROR MESSAGES setStepLicenseKey({ ...getStepLicenseKey, errorMsg: err.data.message, hasError: true });
          }else {
            if (err.errorMsg) {
              // setStepLicenseKey(err)
              console.log(err.errorMsg)
            } else {
              console.error("UNKNOWN ERROR", err);
              
            }
          }
        }
      }
    
      const handleChange = prop => (e) => {
    
        switch (prop) {
          case 'cardNumber':
            setCardNumber(e.target.value)
            break;
          case 'cardName':
            setCardName(e.target.value)
            break;
          case 'cardExpiry':
            setCardExpiry(e.target.value)
            break;
          case 'cardCvv':
            setCardCvv(e.target.value)
            break;
          case 'cardId':
            setCardId(e.target.value)
            break;
            default:
              break;
        }
    
      }
    
      const handleInputFocus = (e) => {
        setFocus( e.target.name );
      }
        
      const handleCardClick = (cardDetail, i) => {
        setCardClick(true)
      }
    
      const delCancel = () => {
        setCardClick(false)
      }
        
    
      const verifyInputs = async function () {
        try {
    
          setLoaderState(true);
          const month = cardExpiry.substring(0, 2);
          const year = `20${cardExpiry.substring(2)}`;
       
          let response = await addCard({
            "cardHolderName": cardName,
            "cardNo": cardNumber,
            "cvv": cardCvv,
            "expiryMonth": month,
            "expiryYear": year,
            "cardId": cardNumber
          })
          if(response.status === StatusCodes.BAD_REQUEST){
          setError(response.data.message)
          
          }
         
         
        // console.log(response,'rt')
    
         else if (response.status === StatusCodes.OK) {
          console.log(response)
          setLoaderState(false)
          setReloadData(true)
          
          loadCardList();
          } else {
            setLoaderState(false)
           
            throw (response);
          }
    
    
        } catch (err) {
          setLoaderState(false);
          
          if (err.data) {
    
            //TODO:: ADD ERROR MESSAGES setStepLicenseKey({ ...getStepLicenseKey, errorMsg: err.data.message, hasError: true });
          }
          else {
            if (err.errorMsg) {
              // setStepLicenseKey(err)
              console.log(err.errorMsg)
            } else {
              console.error("UNKNOWN ERROR", err);
            }
          }
        }
      }
      
      // console.log(getCardsList_CTX,'yy')
     useEffect(()=>{
    
       if(reloadData == true){
        getCardList();
    
    
      }
    console.log(reloadData)
    
     },[reloadData])
     
    
      return (
    
    
        <>
    
    
          <Box display="flex" sx={{
            "width":"1459px","height":"44px","backgroundColor":"#F9FAFA","position":"relative","top":"0px",left:'77px',
          }}></Box>
            {/* TODO ADD CARDS HERE */}
           
            <Box display="flex" sx={{
            "width":"621px","height":"192px","position":"relative","top":"121px",left:'99px',gap:'10px'
            }}>
            {getCardsList_CTX.map((card, index)=>{
    
              return (
                
                <Box width="292px"  height="184px" className={styles.card} onClick={() => handleCardClick(card, index)}>
                  {/* <CancelIcon color="error" sx={{ zIndex: 1, position: 'relative', left: '74%', top: '1%' }} /> */}
                  <Cards
                    key={nanoid()}
                    cvc={card.cvv}
                    expiry={`${card.expiryMonth < 9 ? '0' + card.expiryMonth : card.expiryMonth}${card.expiryYear.toString().substring(2)}`}
                    name={card.cardHolderName}
                    number={`000000000000${card.cardNo.substring(4)}`}
                    issuer={'visa'}
                    preview={true}
                  />
                  {/* <Box position="absolute" width="100%" minHeight="100%" maxHeight="100%" bgcolor="red" zIndex='1'>
    
                  </Box> */}
                  <Box position="absolute" zIndex='2' onClick={() => {handleClickOpen(card)}}>
                    <CancelIcon  sx={{ zIndex: 1,"position":"absolute","left":"263px","top":"-180px",color:"#dbd4d4",cursor:'pointer'  }} />
                  </Box>
                </Box>
              )
          }) }
          </Box>
    
          
    
          
    
          <Box sx={{ "width": "1536px", "height": "1px", "backgroundColor": "#ece5e5", "position": "absolute", "top": "385px" }}></Box>
    
          <Typography mt={5} variant="h3" component="h2" sx={{ "position": "absolute", "top": "24px", "fontSize": "29px", "left": "97px" }}>
            PAYMENT METHOD
          </Typography>
    
          <Typography mt={5} variant="h3" component="h2" sx={{ "position": "absolute", "top": "69px", "fontSize": "24px", "left": "108px", color: '#9C9C9C' }}>
            YOUR SAVED CARDS
          </Typography>
    
          <Box style={{ "position": "absolute", "display": "flex", "top": "431px", "left": "418px" }} id="PaymentForm">
    
            <Typography mt={5} variant="h3" component="h2" sx={{ whiteSpace:'nowrap', "position": "absolute", "top": "-79px", "fontSize": "20px", "left": "307px", color: '#9C9C9C' }}>
              ENTER CARD DETAILS - SAVE/DELETE
            </Typography>
            <Cards
              cvc={cardCvv}
              expiry={cardExpiry}
              focused={focus}
              name={cardName}
              number={cardNumber}
              sx={{ "marginRight": "12px" }}
            />
            <form style={{ width: '333px', marginLeft: '18px' }}>
    
              <TextField type="tel"
                name="number"
                placeholder="Card Number"
                onChange={handleChange('cardNumber')}
                onFocus={handleInputFocus} id="outlined-basic" label="Card Number" variant="outlined"
                sx={{ width: '340px' }}
                inputProps={{ maxLength: 16 }}
                
                
              />
    
                <TextField
                  type="tel"
                  name="name"
                  placeholder="Name"
                  onChange={handleChange('cardName')}
                  onFocus={handleInputFocus}
                  id="outlined-basic" label="Card Holder" variant="outlined"
                  sx={{ "marginTop": "12px", width: '340px' }}
                />
      
             <Box sx={{ "display": "flex", "marginTop": "12px", width: '359px' }}>
                <TextField
                  type="tel"
                  name="expiry"
                  placeholder="Expiry"
                  onChange={handleChange('cardExpiry')}
                  onFocus={handleInputFocus}
                  id="outlined-basic" label="Expiry" variant="outlined"
                  sx={{ "display": "flex", marginRight: '16px', width: '340px' }}
                  inputProps={{ maxLength: 4 }}
    
                />
    
                  <TextField
    
                    type="tel"
                    name="cvc"
                    placeholder="CVV"
                    onChange={handleChange('cardCvv')}
                    onFocus={handleInputFocus}
                    id="outlined-basic" label="CVV" variant="outlined"
                    inputProps={{ maxLength: 3 }}
                    sx={{ marginRight: '19px' }}
                  />        
              </Box>
            </form>
            <Typography mt={5} variant="h3" component="h2" sx={{ whiteSpace:'nowrap', "position": "absolute", "top": "160px", "fontSize": "10px", "left": "312px", color: 'red',textTransform:'uppercase',fontWeight: 'bold',letterSpacing:'2px' }}>
             {error}
            </Typography>
    
            <Button disabled={getLoaderState} onClick={verifyInputs}  variant="contained" disableElevation sx={{  mt: 1, pr: 2 ,"marginTop":"219px","width":"159px","height":"43px","marginLeft":"-241px"}} >
              Save Card {getLoaderState ? <CircularProgress size="1.2em" sx={{ "position": "absolute", right: "0", mr: 2 }} /> : ""}
            </Button>
    
    {/* Payment Card Delete */}
          <Dialog
            open={open}
            onClose={handleClose}
            aria-labelledby="alert-dialog-title"
            aria-describedby="alert-dialog-description"
          >
            <DialogTitle id="alert-dialog-title">
              {"Delete Payment Card"}
            </DialogTitle> 
            <DialogContent>
              <DialogContentText id="alert-dialog-description">
                Are you sure you want to delete your card({deleteCard !== null ? deleteCard.cardNo : ''}), you can't retrive it later on.
              </DialogContentText>
            </DialogContent>
            <DialogActions>
              <Button onClick={handleClose} sx={{ color: 'red' }}>Cancel</Button>
              <Button onClick={handleDeleteCard}>
                Proceed
              </Button>
            </DialogActions>
          </Dialog>
          </Box>
    
          
    
        </>
    
      );
    }
    
    0 回复  |  直到 2 年前
        1
  •  0
  •   Alexander Krum    2 年前

    您需要通知上下文内容已更新。至于React Contact api,您需要更改提供者的状态。

    这里有一篇文章展示了如何使用上下文api。

    https://kentcdodds.com/blog/how-to-use-react-context-effectively