反应本机更新组件

发布于 2025-01-23 08:16:28 字数 7524 浏览 1 评论 0 原文

我对反应的新手很新。当我单击停止睡眠或信息按钮时,我将补丁请求发送到 users.json 文件以更改 status 。我的JSON文件包含;

{
  "users": [
    {
      "hostname": "XXX.XX.XX.XXX",
      "username": "username",
      "password": "admin",
      "command": "whoami",
      "status": "sleep",
      "info": "temp",
      "id": 1
    }
  ]
}

补丁请求已成功发送,但在网页上不重新加载,我看不到新的状态。

import React, { Component } from "react";
import AddUser from "./components/AddUser";
import Users from "./components/Users";
import axios from "axios";



const fs = require('fs');
const path = require('path');

class App extends Component {
    constructor(props) {
        super(props);      

        this.state = {
            users:[],

          };
      
          this.deleteUser = this.deleteUser.bind(this);
          this.addUser = this.addUser.bind(this);
          this.stopPC = this.stopPC.bind(this);
          this.infoPC = this.infoPC.bind(this) ;
          

    }

    async componentDidMount(){
        const response = await axios.get("http://localhost:3002/users");
       // console.log(response);
       this.setState({users:response.data})
    }

     componentWillUnmount(){
      clearInterval(this.interval);
    } 
    

    async statusUpdate(){
      const response = await axios.get("http://localhost:3002/users");
     // console.log(response);
     this.interval = setInterval(() => this.setState({users:response.data.status}),3000)
  }
   
      //AXIOS API
      deleteUser = async (id) => {
        axios.delete('http://localhost:3002/users/'+ id);
       
        let updatedUsers = this.state.users;
        updatedUsers = updatedUsers.filter(user => user.id !== id);
        
        this.setState({
          users : updatedUsers
        })
    
      }

    
      addUser(newUser){
        
        axios({
          method: 'post',
          url: 'http://localhost:3002/users/',
          data: {
            hostname: newUser.hostname,
            username : newUser.username,
            password: newUser.password,
            command : newUser.command,
            status : newUser.status
          }    
        });

        let updatedUsers = this.state.users;
        updatedUsers.push(newUser);
    
        this.setState({
          users : updatedUsers
        })
    
      }

      stopPC(id){
            axios.patch('http://localhost:3002/users/'+id, {
              command:  'shutdown -s -t 0',
            });    
      }

      sleepPC(id){
          axios.patch('http://localhost:3002/users/'+id, {
            command:  'rundll32.exe user32.dll,LockWorkStation',
            status : 'sleep'
          });    
      }

      infoPC(id){
        axios.patch('http://localhost:3002/users/'+id, {
          command:  'whoami',
          status : 'info'
        });    
    }

   


    render() {
        const title = "Remote Control"
        return (
            <div className="container">
            <h1>{title}</h1>
            <hr/>
            <AddUser addUser= {this.addUser}/>
            <hr/>
            <Users deleteUser= {this.deleteUser} users = {this.state.users} stopPC= {this.stopPC} sleepPC= {this.sleepPC}  infoPC={this.infoPC} statusUpdate={this.statusUpdate} />
      </div>
        );
    }
}

export default App;

这是我的用户。

import React , {Component} from "react";
import User from "./User";
class Users extends Component  {
    render(){
        const {users , deleteUser,stopPC,sleepPC,infoPC} = this.props;
        return(
            <table className="table table-dark">
  <thead>
    <tr>
      <th scope="col">ID</th>
      <th scope="col">Hostname</th>
      <th scope="col">Username</th>
     
      <th scope="col">Stop</th>
      <th scope="col">Sleep</th>
      <th scope="col">Start</th>
      <th scope="col">Status</th>
      <th scope="col">CPU Temperature</th>
      <th scope="col">Info</th>
      <th scope="col">Delete</th>


    </tr>
  </thead>

  <tbody>
            {
                users.map(user => {
                    const {id,hostname,username,password,command,status,info} = user;
                    return <User key={id}
                        id = {id}
                        hostname = {hostname}
                        username = {username}
                        password = {password}
                        command = {command}
                        status={status}
                        info={info}
                        deleteUser = {deleteUser}
                        stopPC={stopPC}
                        sleepPC = {sleepPC}
                        infoPC = {infoPC}
                    />;
                 })
            }
  </tbody>

</table>
        )
    }
}
export default Users;

和我的user.js文件;

import React , {Component} from "react";
import Popup from "./Popup";
const axios = require('axios');
const fs = require('fs');
const path = require('path');


class User extends Component  {

    constructor(props) {
        super(props);
        this.state = {
            buttonPopup: false
        };
      }
   

    onDeleteClick(id,e){
        const {deleteUser} =  this.props;

        deleteUser(id);
        
    }

    onStopClick(id,e){
        const {stopPC} =  this.props;

        stopPC(id);
        
    }

    onSleepClick(id,e){
        const {sleepPC} =  this.props;

        sleepPC(id);
        
    }

    onStartClick(id,e){
        
    }

    buttonPopupfunc(id,e){
        this.setState({buttonPopup : true})
    }

    infofunc(id,e){
        const {infoPC} =  this.props;

        infoPC(id);
    }
   
    render(){
        const {id,hostname,username,status,info,cpuTemp} = this.props;

        return(
            <tr>
                <td>{id}</td>
                <td>{hostname}</td>
                <td>{username}</td>      
                <td><button onClick={() =>{this.onStopClick.bind(this,id);document.location.reload(true)}} className="btn btn-danger">Stop</button></td>
                <td><button onClick={this.onSleepClick.bind(this,id)} className="btn btn-warning">Sleep</button></td>
                <td><button onClick={this.onStartClick.bind(this,id)} className="btn btn-success">Start</button></td>
                <td>{status}</td>
                <td>{cpuTemp}</td>
                <td><button  onClick={() => {this.buttonPopupfunc();this.infofunc(id);}} type="button" class="btn btn-info">&#128712;</button>
                
                <Popup trigger = {this.state.buttonPopup} setTrigger = {() =>this.setState({buttonPopup : false})} >
                <text>{this.infos}</text>
                </Popup>
                
                </td>
            
                <td><button onClick={this.onDeleteClick.bind(this,id)} className="btn btn-danger">Delete</button></td>



            </tr>
            
        )
    }
}

export default User;

我想看到网页上的状态即时更改。如果您有帮助,我会很高兴。这是我的网页;

网页

I'm pretty new to react-native. When I click the stop sleep or info button I send patch requests to the users.json file to change the status. My JSON file contains ;

{
  "users": [
    {
      "hostname": "XXX.XX.XX.XXX",
      "username": "username",
      "password": "admin",
      "command": "whoami",
      "status": "sleep",
      "info": "temp",
      "id": 1
    }
  ]
}

Patch request sends successfully but on a web page without reloading, I cant see new status.Here is my App.js file;

import React, { Component } from "react";
import AddUser from "./components/AddUser";
import Users from "./components/Users";
import axios from "axios";



const fs = require('fs');
const path = require('path');

class App extends Component {
    constructor(props) {
        super(props);      

        this.state = {
            users:[],

          };
      
          this.deleteUser = this.deleteUser.bind(this);
          this.addUser = this.addUser.bind(this);
          this.stopPC = this.stopPC.bind(this);
          this.infoPC = this.infoPC.bind(this) ;
          

    }

    async componentDidMount(){
        const response = await axios.get("http://localhost:3002/users");
       // console.log(response);
       this.setState({users:response.data})
    }

     componentWillUnmount(){
      clearInterval(this.interval);
    } 
    

    async statusUpdate(){
      const response = await axios.get("http://localhost:3002/users");
     // console.log(response);
     this.interval = setInterval(() => this.setState({users:response.data.status}),3000)
  }
   
      //AXIOS API
      deleteUser = async (id) => {
        axios.delete('http://localhost:3002/users/'+ id);
       
        let updatedUsers = this.state.users;
        updatedUsers = updatedUsers.filter(user => user.id !== id);
        
        this.setState({
          users : updatedUsers
        })
    
      }

    
      addUser(newUser){
        
        axios({
          method: 'post',
          url: 'http://localhost:3002/users/',
          data: {
            hostname: newUser.hostname,
            username : newUser.username,
            password: newUser.password,
            command : newUser.command,
            status : newUser.status
          }    
        });

        let updatedUsers = this.state.users;
        updatedUsers.push(newUser);
    
        this.setState({
          users : updatedUsers
        })
    
      }

      stopPC(id){
            axios.patch('http://localhost:3002/users/'+id, {
              command:  'shutdown -s -t 0',
            });    
      }

      sleepPC(id){
          axios.patch('http://localhost:3002/users/'+id, {
            command:  'rundll32.exe user32.dll,LockWorkStation',
            status : 'sleep'
          });    
      }

      infoPC(id){
        axios.patch('http://localhost:3002/users/'+id, {
          command:  'whoami',
          status : 'info'
        });    
    }

   


    render() {
        const title = "Remote Control"
        return (
            <div className="container">
            <h1>{title}</h1>
            <hr/>
            <AddUser addUser= {this.addUser}/>
            <hr/>
            <Users deleteUser= {this.deleteUser} users = {this.state.users} stopPC= {this.stopPC} sleepPC= {this.sleepPC}  infoPC={this.infoPC} statusUpdate={this.statusUpdate} />
      </div>
        );
    }
}

export default App;

Here is my Users.js file;

import React , {Component} from "react";
import User from "./User";
class Users extends Component  {
    render(){
        const {users , deleteUser,stopPC,sleepPC,infoPC} = this.props;
        return(
            <table className="table table-dark">
  <thead>
    <tr>
      <th scope="col">ID</th>
      <th scope="col">Hostname</th>
      <th scope="col">Username</th>
     
      <th scope="col">Stop</th>
      <th scope="col">Sleep</th>
      <th scope="col">Start</th>
      <th scope="col">Status</th>
      <th scope="col">CPU Temperature</th>
      <th scope="col">Info</th>
      <th scope="col">Delete</th>


    </tr>
  </thead>

  <tbody>
            {
                users.map(user => {
                    const {id,hostname,username,password,command,status,info} = user;
                    return <User key={id}
                        id = {id}
                        hostname = {hostname}
                        username = {username}
                        password = {password}
                        command = {command}
                        status={status}
                        info={info}
                        deleteUser = {deleteUser}
                        stopPC={stopPC}
                        sleepPC = {sleepPC}
                        infoPC = {infoPC}
                    />;
                 })
            }
  </tbody>

</table>
        )
    }
}
export default Users;

And my User.js file;

import React , {Component} from "react";
import Popup from "./Popup";
const axios = require('axios');
const fs = require('fs');
const path = require('path');


class User extends Component  {

    constructor(props) {
        super(props);
        this.state = {
            buttonPopup: false
        };
      }
   

    onDeleteClick(id,e){
        const {deleteUser} =  this.props;

        deleteUser(id);
        
    }

    onStopClick(id,e){
        const {stopPC} =  this.props;

        stopPC(id);
        
    }

    onSleepClick(id,e){
        const {sleepPC} =  this.props;

        sleepPC(id);
        
    }

    onStartClick(id,e){
        
    }

    buttonPopupfunc(id,e){
        this.setState({buttonPopup : true})
    }

    infofunc(id,e){
        const {infoPC} =  this.props;

        infoPC(id);
    }
   
    render(){
        const {id,hostname,username,status,info,cpuTemp} = this.props;

        return(
            <tr>
                <td>{id}</td>
                <td>{hostname}</td>
                <td>{username}</td>      
                <td><button onClick={() =>{this.onStopClick.bind(this,id);document.location.reload(true)}} className="btn btn-danger">Stop</button></td>
                <td><button onClick={this.onSleepClick.bind(this,id)} className="btn btn-warning">Sleep</button></td>
                <td><button onClick={this.onStartClick.bind(this,id)} className="btn btn-success">Start</button></td>
                <td>{status}</td>
                <td>{cpuTemp}</td>
                <td><button  onClick={() => {this.buttonPopupfunc();this.infofunc(id);}} type="button" class="btn btn-info">🛈</button>
                
                <Popup trigger = {this.state.buttonPopup} setTrigger = {() =>this.setState({buttonPopup : false})} >
                <text>{this.infos}</text>
                </Popup>
                
                </td>
            
                <td><button onClick={this.onDeleteClick.bind(this,id)} className="btn btn-danger">Delete</button></td>



            </tr>
            
        )
    }
}

export default User;

I want to see the instant change in status on the web page.I will be glad if you help. Here is my web page;

web page

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

神仙妹妹 2025-01-30 08:16:28

此处的问题是,您尚未更新用户在随后的方法 stoppc sleeppc 状态更改后的状态更改后的状态更改。 > infopc 这就是为什么即使服务器中的状态已更改,也不会反映在网页中的原因。

修补程序操作后,您可以发送更新的用户对象,然后更新用户状态:

sleepPC = async (id) => {
  const res = await axios.patch('http://localhost:3002/users/'+id, {
    command:  'rundll32.exe user32.dll,LockWorkStation',
    status : 'sleep'
  );  
  this.setState({ users: res })
}

或简单地将布尔值传递给相同的布尔值,然后在前端本身中更新以更改状态的用户:

sleepPC = async (id) => {
  const res = await axios.patch('http://localhost:3002/users/'+id, {
    command:  'rundll32.exe user32.dll,LockWorkStation',
    status : 'sleep'
  );  
  if (res) {
    this.setState({
      users: this.state.users.map(user => user.id === id ? { ...user, status: 'sleep' } : user)
    }) 
  }
}

The issue here is you have not updated the users state following the status change after the patch request in the subsequent methods stopPC, sleepPC and infoPC which is why even though the status has changed in the server, it does not reflect in the webpage.

You can send the updated users object after the patch operations and update the users state with that :

sleepPC = async (id) => {
  const res = await axios.patch('http://localhost:3002/users/'+id, {
    command:  'rundll32.exe user32.dll,LockWorkStation',
    status : 'sleep'
  );  
  this.setState({ users: res })
}

or simply pass a boolean for the same and update the user with the changed status in the frontend itself:

sleepPC = async (id) => {
  const res = await axios.patch('http://localhost:3002/users/'+id, {
    command:  'rundll32.exe user32.dll,LockWorkStation',
    status : 'sleep'
  );  
  if (res) {
    this.setState({
      users: this.state.users.map(user => user.id === id ? { ...user, status: 'sleep' } : user)
    }) 
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文