全局变量在 React 渲染中不更新

问题描述 投票:0回答:0

我在客户端工作,由于某种原因我无法获得

update
函数来更改全局变量。它在控制台中显示新值,但在控制台或网页上打印时不显示。我觉得我的头撞到墙上了。

App.js

import React, { useContext } from 'react';
import { Button, Container, Card, Row } from 'react-bootstrap'
import toast from 'react-simple-toasts';
import axios from 'axios';
import '../App.css';

import { CasUserContext } from "../context/casUserContext";
import useCas from "../components/Cas";

export default function Main(){
    const cas = useCas();
    const {user} = useContext(CasUserContext);

    var state = {
        setWatiam: '',
        setFullname: '',
        setTeam: '',
        fetchData: [],
        teamUpdate: ''
    };
    
    var reloadToast = (msg) => {
        sessionStorage.setItem('reloadtoast', msg);
        document.location.reload()
    };
    
    var handleChange = (event) => {
        let nam = event.target.name;
        let val = event.target.value
        state[nam] = val
    };
    
    var handleTeamChange = (event) => {
        // const {state} = useContext(MainPageContext);
        // let state = MainPageContext.state
        state.teamUpdate = event.target.value
    };
    
    var update = () => {
        // const {state} = useContext(MainPageContext);
        // let state = MainPageContext.state
        // console.log(MainPageContext)
        axios.get('/api/get-fy').then((response) => {
            state.fetchData = response.data
            console.log(`Fetched data: ${state.fetchData[0]["watiam"]}`) <<<<<<<<<<<<<< This Log!
            })
        // Present Toast message from previous action
        if (sessionStorage.getItem('reloadtoast')) {
            // Restore the contents of the text field
            toast(sessionStorage.getItem('reloadtoast'), 5000)
            sessionStorage.removeItem('reloadtoast')
        }
    }
    
    var submit = () => {
        // const {state} = useContext(MainPageContext);
        // let state = MainPageContext.state
        axios.post('/api/fy-add', state).then(response => {
            if (response.status === 200)
            reloadToast(`Sucessfully added '${state.setWatiam}' to database`);
            else toast("Error, Not Added")
        })
    }
    
    var _delete = (watiam) => {
        if (window.confirm("Do you want to delete? ")) {
            axios.delete(`/api/delete/${watiam}`, state).then(response => {
                if (response.status === 200)
                    reloadToast(`Sucessfully Deleted '${watiam}' from database`);
                else toast("Error, Not Deleted");
            })
        }
    }
    
    var edit = (watiam) => {
        console.log("Edit")
        axios.put(`/api/update-fy/${watiam}`, state).then(response => {
            if (response.status === 200)
            reloadToast(`Sucessfully Updated '${watiam}' to team '${this.state.teamUpdate}'`);
            else toast("Error, Not Updated");
        })
    }

    console.log(`Cas User: ${user}`)
    update()
    console.log(`Data: ${state.fetchData}`) <<<<<<<<<<<<<< This Log!
    let card = state.fetchData.map((val) => {
    return (
        <React.Fragment key={`card_${val.watiam}`}>
        <Card style={{ width: '18rem' }} className='m-2' >
            <Card.Body>
            <Card.Title>{val.name}</Card.Title>
            <Card.Text>
                Student ID: {val.watiam} <br></br>
                Full Name: {val.fullname} <br></br>
                Colour Team: {val.team} <br></br>
            </Card.Text>
            <input name='teamUpdate' onChange={handleTeamChange} placeholder='Change Colour Team' ></input>
            <Button className='m-2' onClick={() => { edit(val.watiam) }}>Update</Button>
            <Button onClick={() => { _delete(val.watiam) }}>Delete</Button>
            </Card.Body>
        </Card>
        </React.Fragment>
    )
    })

    return (
        <div>
        {/* <Layout background="status-ok" isSecure={true}> */}
            <button id="login" onClick={() => {
                cas.attemptCasLogin(false);
            }}>Log In</button>
            <button id="refresh" onClick={() => document.location.reload()}>Update List</button>
            <h1>FY and Leader Database</h1>
            <h2> User is {user}</h2>
            <div className='form'>
                <input name='setFullname' placeholder='Enter First Year Name' onChange={handleChange} />
                <input name='setWatiam' placeholder='Enter First Year Watiam' onChange={handleChange} />
                <input name='setTeam' placeholder='Enter First Year Colour Team' onChange={handleChange} />
            </div>

            <Button className='my-2' variant="primary" onClick={() => {
                submit()
            }}>Submit</Button> <br /><br/>

            <Container>
            <Row>
                {card}
            </Row>
            </Container>
        {/* </Layout> */}
        </div>
    )
}

我尝试过使用上下文,但我对 javascript 太陌生了,它们融化了我的大脑。我不需要其他文件中的此信息,只需要此页面。全局变量应该可以正常工作吗?

javascript reactjs variables
© www.soinside.com 2019 - 2024. All rights reserved.