首页 > 解决方案 > 当服务器上的事件发生时如何更新 ReactJs 中的 prop 状态

问题描述

我有一个 ExpressJs 服务器和一个前端 React 应用程序。React 应用程序有一个切换按钮,它在状态更改时使用 URL 中的请求参数向服务器发出 get 请求。服务器处理请求并通过 GPIO 端口切换物理继电器(开关)。

我遇到的问题是我还配置了一个由 Google 助理 (IFTTT) 触发的 webhook,它可以切换开关状态。这会使 React 应用程序和交换机的实际状态不同步。当服务器通过 IFTTT 接收请求时,有没有办法可以更新所有打开的 Web 会话(在 React 应用程序上)上的 prop 变量的状态。

快递服务器代码

const express = require('express');
const app = express();
const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`Listening on port ${port}`));

app.get('/express_backend', (req, res) => {
  
  //switch the Relay Switch (jname) as per state (jstate):(on, off)
  //then reply to req: res.send({ jstate: sState, jname: sName });
  
  switchController.setSwitch(req.query['jstate'], req.query['jname'],req.query['jaction'], res);

}

ReactJs WebApp 代码

class ToggleSwitch extends Component {

  componentDidMount() {
    this.postToServer(this.props.id,'','get');
  }

  constructor() {
    super();
    this.state = { checked: false };
    this.handleChange = this.handleChange.bind(this);
  }
  
  callBackendAPI = async (switchName, switchState, switchAction) => {
  
    var getUrl = '/express_backend?jname='+switchName + '&jstate='+switchState + '&jaction='+switchAction;
    const response = await fetch(getUrl,{method: 'get'});
	if (response.status === 200) return await response.json();
  };
  
  postToServer(switchName, switchState, switchAction){
  
    this.callBackendAPI(switchName, switchState, switchAction)
      .then(res => this.setState({checked: (res.jstate === 'true')}))
      .catch(err => console.log(err));

  }
 
  handleChange(checked, event,id) {
    this.postToServer(id,checked,'set');
  }
 
  render() {
    return (
    <div>
    <div style = {{fontSize: '18px', textAlign: 'center', width: '165px', paddingBottom: '5px'}}>{this.props.name}</div>
    <div style = {{height: '50',display: 'flex', alignItems: 'center'}}>
    <Switch
        checked={this.state.checked}
        onChange={this.handleChange}
        height={50}
        width={115}
        className="react-switch"
        id={this.props.id}
      />
	</div>
	</div>
    );
  }
}

标签: reactjsexpresswebhooks

解决方案


您是否尝试过使用类似的 websocket

npm socket.io


推荐阅读