简体   繁体   中英

Context API is not Changing it's State at Global Level in React

This is My App.js File


import 'bootstrap/dist/css/bootstrap.min.css';
import Run from './Signupin/mainpage';
import Exp from './afterlogin/patirel/patmain';
import Exp1 from './afterlogin/adminrel/designdb';
import Exp2 from './afterlogin/adminrel/consult';
import Exp3 from './afterlogin/adminrel/support';
import Exp4 from './afterlogin/patirel/one';
import PostRequest from './afterlogin/adminrel/one';
import Docc from './afterlogin/docrel/one';
import {Routes,Route} from 'react-router-dom';
import Done from "./appointment/appointment";
import * as React from 'react';




function App() {
 

  return (

    <div>
    <Routes>
      <Route index element={<Run/>} />
      <Route path="/patmain" element={<Exp/>} />
      <Route path="/adco" element={<PostRequest/>} />
      <Route path="/adco1" element={<Exp1/>} />
      <Route path="/adco2" element={<Exp2/>} />
      <Route path="/adco3" element={<Exp3/>} />
      <Route path="/adco4" element={<Exp4/>} />
      <Route path="/docc1" element={<Docc/>} />
      <Route path="/appoint" element={<Done/>} />
    </Routes>
    </div>
 

  );
}

export default App;

My index.js file

import React from 'react';
import ReactDom from 'react-dom';
import './index.css';
import App from './App';
import {BrowserRouter} from 'react-router-dom';
import {Appointment} from "./appointment/Context"


ReactDom.render(<BrowserRouter><Appointment><App /></Appointment></BrowserRouter>, document.querySelector('#root'));


My Context Provider file where the state emailinfo is not being updated in this file

import {createContext,useState } from 'react';
import * as React from 'react';






export const Contextforabhishek= createContext({});

 
export const Appointment=({children})=>{

 
  const [emailinfo, setemailinfo] = useState("NA");//Not Getting Updated at Global Level



  const yy={emailinfo,setemailinfo}

return(
  <>
  <Contextforabhishek.Provider value={yy} >{children}</Contextforabhishek.Provider>
  
  </>
);


}

This is the file from where i want the data, file Patmain to File Appointment. I am using useContext inside this.

import "./Appyss.css";
import { Button, Modal, Dropdown} from "react-bootstrap";
import { useState, useEffect,useContext} from "react";
import { Contextforabhishek } from '../../appointment/Context';
import * as React from 'react';
//import { Link } from 'react-router-dom'



function Patmainss(props) {

  return (
    <div className="forall">
    <Modal
      {...props}
      size="lg"
      aria-labelledby="contained-modal-title-vcenter"
      centered
    >
      <Modal.Header closeButton>
        <Modal.Title id="contained-modal-title-vcenter">
        {props.title} {props.Introduction}
        </Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <p>{props.Description}</p>
      </Modal.Body>
      <Modal.Footer>
        <Button onClick={props.onHide}>Close</Button>
      </Modal.Footer>
    </Modal>
    </div>
  );
}



function Patmain() {

 const {emailinfo,setemailinfo }=useContext(Contextforabhishek);
 const infor=(e)=>{
  const m=e.target.id;
  setemailinfo(m);
}


console.log(emailinfo);{/* THE STATE IS BEING CHANGED HERE BUT THAT SAME STATE IS NOT OBTAINABE AT FILE APPOINTMENT*/}
    

  const [runing, setRuning] = useState(
    {
      runing:"2"
    },
  );




  const Runing = (e) => {
    setRuning({
     runing:"2"
     
    });
  };  
  
  const [modalShow, setModalShow] = useState(false);
  const [Fetchdoc, setFetchdoc] = useState([
    {
   
    },
  ]);

  const [doct, setDoct] = useState({
    First_Name: "",
    Intro:"",
    Description: "",
    Check_Up_Address:""
  });


  const [renn,setRenn] = useState({
    renn:"a",
  });

  const handleRenn = (e) => {
    Runing();
    setRenn({
     renn:"a",
     
    });
  };  

  const handleRenn1 = (e) => {
    Runing();
    setRenn({
     renn:"aa",
    
    });
    
  };  

  const handleRenn2 = (e) => {
    Runing();
    setRenn({
     renn:"aaa"
    });
    
  };  

  const handleRenn3 = (e) => {
    Runing();
    setRenn({
     renn:"aaaa"
    });
   
  };  

  const handleRenn4 = (e) => {
    Runing();
    setRenn({
     renn:"aaaaa"
    });
   
  };  

  

  useEffect(() => {
    if(runing.runing==="2")
    {
  
    if(renn.renn==="a"){
    fetch("http://localhost:8001/docconfirmed")
      .then((res) => res.json())
      .then((jsonRes) => setFetchdoc(jsonRes),[]);}
    else if(renn.renn==="aa"){


      const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ practice:'Orthopaedic' })

    };
    fetch('http://localhost:8001/docconfirmed1',requestOptions )
        .then(response => response.json())
        .then((jsonRes) => setFetchdoc(jsonRes));


    }
    else if(renn.renn==="aaa"){


      const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ practice:'Paediatrician' })
    };
    fetch('http://localhost:8001/docconfirmed1',requestOptions )
        .then(response => response.json())
        .then((jsonRes) => setFetchdoc(jsonRes));


    }
    else if(renn.renn==="aaaa"){


      const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ practice:'General-Physician' })
    };
    fetch('http://localhost:8001/docconfirmed1',requestOptions )
        .then(response => response.json())
        .then((jsonRes) => setFetchdoc(jsonRes));


    }
    else if(renn.renn==="aaaaa"){


      const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ practice:'Audiologist' })
    };
    fetch('http://localhost:8001/docconfirmed1',requestOptions )
        .then(response => response.json())
        .then((jsonRes) => setFetchdoc(jsonRes));


    }
    runing.runing="stop";
   
  }
    
  });

  const handleClick = (e) => {
    setModalShow(true);
    const { name, alt,id} = e.target;
    
    

    setDoct({
      First_Name: name,
      Intro: id,
      Description: alt,
    });
  };
  
 

  return (
    <div>
    <div className="column">
      <h2 style={{color:'purple',fontWeight: 'bold'}} className="msgs">Click On The Images To Get More Details On Your-Aid Doctors</h2>
      <div style={{marginLeft : 50, marginTop : 20, marginDown : 90,  display: "block", width: "30%", height: "40%" }}>
    <Dropdown>
    <Dropdown.Toggle variant="primary" id="dropdown-basic" style={{paddingTop : 12,paddingLeft : 795, paddingBottom : 12, paddingRight : 20, paddingDown : 100, }}>
    <h4 style={{textAlign: 'left',color:'black'}}>
      Click Here To Choose The Required Specialisation
      </h4>
    </Dropdown.Toggle>
    <Dropdown.Menu>
      <Dropdown.Item onClick={handleRenn}>View All Doctors</Dropdown.Item>
      <Dropdown.Item onClick={handleRenn1}>Orthopaedic</Dropdown.Item>
      <Dropdown.Item onClick={handleRenn2}>Paediatrician</Dropdown.Item>
      <Dropdown.Item onClick={handleRenn3}>General-Physician</Dropdown.Item>
      <Dropdown.Item onClick={handleRenn4}>Audiologist</Dropdown.Item>
    </Dropdown.Menu>
  </Dropdown>
  </div>

      <div
        className="forall"
      >
        {Fetchdoc
          .sort((a, b) => {
            var titleA = a.title;
            var titleB = b.title;
            if (titleA < titleB) {
              return -1;
            }
            if (titleA > titleB) {
              return 1;
            }
            return 0;
          })
          .map((doct) =>{

            const First=doct.First_Name;
            const Last=doct.Last_Name;
            const Lasts=doct.practice;
           //const Emaill=doct.Email;
            return (
              // handleEmailInfo(e.target.id)}
                <l1><ul><button onClick={infor} className="btn btn-dark" style={{marginLeft : 200, marginTop : 80, display: "block", width: "15%", height: "40%" }} id={doct.Email} >Book An Appointment With { First }</button>

              <div className="mores">
    
                  <img
                    //key={/**/}
                    id={" ( Call@" +String(doct.Doctors_Phone)+" )"}
                    src={doct.Image}
                    alt={String(doct.Description)+" Email-ID@ "+String(doct.Email)}
                    name={String(doct.First_Name)+" "+String(doct.Last_Name)}
                    width="260" 
                    height="190"
                    onClick={handleClick}
                  ></img>
                  <l1 style = {{ marginLeft : 20, color:'black', 'font-size': '32px',fontWeight:100}} > {String(First)+" "+String(Last)}<ul style={{ marginTop : 10, color:'white', 'font-size': '26px',fontWeight:80}}>{String(Lasts)}</ul></l1> 
                  <br></br>
                  <br></br>
  
  
                    </div>
                    </ul></l1>
            );

          })}
      </div>
      
      <Patmainss
        show={modalShow}
        onHide={() => setModalShow(false)}
        title={doct.First_Name}
        Introduction={doct.Intro}
        Description={doct.Description}
      />
  
    
    </div>
    </div>
  );
  
}



export default Patmain;


file Appointment where i want the Context Data to be but the state is always at NA emailinfo doesn't change the state at global level

import * as React from 'react';
import {useContext } from 'react';
import { Contextforabhishek } from './Context';


export default function All(){

  const {emailinfo}=useContext(Contextforabhishek);//state is unchanged trying to change the state in Patmain file there it changes but here it doesn't change


  console.log("obtained",emailinfo)
  return(
    <div>

   <h1>(Done Page) Book an Appointment with: {emailinfo}</h1>
   {/* <button onClick={(e)=>{setemailinfo("ll")}}>click</button> */}
    </div>

  );
}

It's been days and still cannot figure out why this is happening please help me out

在所有组件中,您似乎没有从上下文中提取 setEmailInfo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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