我正在使用 React 和 PHP,我需要它来做一些特定的事情。我正在使用 Axios 向我的 PHP 页面发送请求,然后更改我的数据库。我需要更新我的 MySQL 数据库表,如果用户关闭页面或浏览器,则将is_logged值从true更改为false 。执行此操作的代码在窗口的beforeunload事件中设置。但是,数据库永远不会更新。我想要做的事情在 React 中是可能的吗?
这是我的 React 组件代码:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Viewers from './Viewers';
const Live = ({ match }) => {
window.addEventListener("beforeunload", () => {
axios.get('http://localhost/live-streaming-app/get_viewers.php?=' + token)
.then(response => console.log(response))
})
// Set token from url
const token = match.params.token
//Get the fullname and update logged_in to true
const [fullname, setFullname] = useState("")
useEffect(() => {
axios.get('http://localhost/live-streaming-app/get_user.php?token=' + token)
.then(response => {
setFullname(response.data.fullname)
console.log("Data", response.data)
})
.catch(error => console.log(error))
return () => {
axios.get('http://localhost/live-streaming-app/get_viewers.php?=' + token)
.then(response => console.log(response))
.catch(error => console.log(error))
}
}, [token])
//Jsx for when user is unauthorised
const rejected = (
<div className="container text-center pt-5">
<h1>Rejected Connection</h1>
<p>You are unauthorised to view this page</p>
</div>
)
let my_render = ""
if (fullname && fullname != null) {
my_render = <Viewers fullname={fullname} />
} else {
my_render = rejected
}
return my_render
};
export default Live;
这是名为的 PHP 页面:
<?php
require 'connect.php';
$token = $_GET['token'];
$sql = "UPDATE `viewers` SET `logged_in`='false' WHERE `live_token`='{$token}'";
if(mysqli_query($con, $sql)){
http_response_code(201);
}
else {
http_response_code(422);
}
exit;
芜湖不芜
慕森卡