使用 Reactjs 和 Nodejs 基于station_id获取和显示device_id

Fetch and display device_id based on station_id using Reactjs and Nodejs

提问人:Lavanya 提问时间:11/17/2023 更新时间:11/17/2023 访问量:6

问:

根据station_id获取和显示device_id 我尝试添加新组件并将 prop 传递给 Parent(Home) 组件,但无法过滤 根据station_id选择device_id数据。需要同时选择station_id和device_id 选择。 getChargingStationData() -> API 同时具有station_id和device_id数据


    import { useEffect, useState } from 'react';
    import Button from 'react-bootstrap/Button';
    import Operation from '../../components/Operation/Operation';
    import {
    getChargingStationData,
    InitiateConnection,
    } from '../../controller/REST';
    import { socketArray, csDetails } from '../../controller/globals';
    import Container from 'react-bootstrap/Container';
    import Row from 'react-bootstrap/Row';
    import Col from 'react-bootstrap/Col';
    import Form from 'react-bootstrap/Form';
    import Card from 'react-bootstrap/Card';

    let ChargingStationValue = '';
    let listOfChargingStation = [];

   const ChargingStationSelect = ({ onSelect }) => {
    const [activeChargeStation, setActiveChargeStation] = useState('');
    const [chargeStationList, setChargeStationList] = useState([]);

    useEffect(() => {
    async function get() {
      const data = await getChargingStationData();
      if (data['data'] !== chargeStationList) {
        listOfChargingStation = data['data'];
        setChargeStationList(data['data']);
        console.log("setChargeStationList",data['data']);
      }
    }
    get();
    }, []);

    const handleChange = (e) => {
     ChargingStationValue = e.target.value;
     setActiveChargeStation(e.target.value);
    };
    return (
    <Form.Select value={activeChargeStation} onChange={handleChange}>
      <option value=''>Select</option>;
      {chargeStationList.map((station, index) => {
        return (
          <option key={index} value={station['device_id']}>
            {station['device_id']}
          </option>
        );
      })}
    </Form.Select>
    );
    };

   export default function Home() {
    const [chargingStationInstances, setChargingStationInstances] = useState([]);
    const [activeChargingStation, setActiveChargingStation] = useState();
   let stationDetailsMap = new Map()
    const [chargeStationList, setChargeStationList] = useState([]);
    const [testData,setTestData] = useState();
 
    const handleStationSelect = (deviceId) => {
    setActiveChargingStation(deviceId);
     
    };

    const [message, setMessage] = useState({
    flag: false,
    color: '',
    message: '',
    });

    useEffect(() => {
    if (message['flag'] === true) {
      setTimeout(() => {
        setMessage({
          flag: false,
          color: '',
          message: '',
        });
      }, 3000);
      }
     }, [message]);

    useEffect(() => {
    async function getConn() {
      let temp = [];
      for (const i in socketArray) {
        let tempCs = csDetails[i];
        temp.push(tempCs);
      }
      if (chargingStationInstances !== temp) {
        setChargingStationInstances(temp);
      }
    }
    getConn();
    
    }, []);

    const handleExecuteOperation = () => {
    if (ChargingStationValue === '') {
      setMessage({
        flag: true,
        color: 'Red',
        message: 'Please select a charging station',
      });
      return;
    }

    async function get() {
      let tempOperations;
      try {
        const data = await InitiateConnection({
          device_id: ChargingStationValue,
        });
        tempOperations = data['data'];
        const envURL = process.env.REACT_APP_SOCKETURL;
        const ws = new WebSocket(`${envURL}/${tempOperations['device_id']}`);
        socketArray[tempOperations['device_id']] = ws;
        tempOperations['ws'] = ws;
        csDetails[ChargingStationValue] = tempOperations;
        if (tempOperations) {
          setChargingStationInstances((prevState) => [
            ...prevState,
            tempOperations,
          ]);
        } else {
          setMessage({
            flag: true,
            color: 'Red',
            message: 'Please select a charging station',
          });
        }
      } catch (e) {
        setMessage({
          flag: true,
          color: 'Red',
          message: e.response.data,
        });
      }
     }
      get();
     };

     const handleRemoveInstance = (chargingStation) => {
      for (let i = 0; i < chargingStationInstances.length; ++i) {
        if (chargingStationInstances[i] === chargingStation) {
        setChargingStationInstances([
          ...chargingStationInstances.slice(0, i),
          ...chargingStationInstances.slice(i + 1),
        ]);
        delete socketArray[chargingStation?.device_id];
        break;
       }
      }
    setMessage({
      flag: true,
      color: 'Green',
      message: `Charging station ${chargingStation['device_id']} is deleted successfully`,
     });
     };

    const reconnectChargingStationInstance = (chargingStationInstance) => {
    handleRemoveInstance(chargingStationInstance);
    ChargingStationValue = chargingStationInstance.device_id;
    handleExecuteOperation();
    return;
    };

    return (
    <Container fluid>
      <Row className="justify-content-center">
        <Card
          className="shadow-lg p-3 mb-2 bg-white rounded"
          style={{
            width: '100%',
            padding: '10px',
            overflow: 'auto',
          }}
        >
          {/* <GroupInstancesCollection/> */}
          <Row className="justify-content-start">
          <Col style={{
                      fontSize: '15px',
                    }} xs={12} sm={6} md={3}>
              Select Station ID
            </Col>
            <Col style={{
                      fontSize: '15px',
                    }} xs={12} sm={6} md={3}>
              Select Charging Station
            </Col>
          </Row>
          <Row className="justify-content-start">
          
            </Col>
            <Col xs={12} sm={6} md={3}>
              <ChargingStationSelect onSelect={handleStationSelect} />
            </Col>
            
            <Col xs={12} sm={6} md={3}>
              <Button
                style={{
                  height: '100%',
                  width: '100%',
                }}
                onClick={handleExecuteOperation}
                variant="primary"
              >
                Add Instance
              </Button>
            </Col>
          </Row>
          {message['flag'] === true ? (
            <Row
              style={{
                color: message['color'],
              }}
              className="justify-content-center"
            >
              {message['message']}
            </Row>
          ) : (
            <></>
          )}
        </Card>
      </Row>
      <Row
        className="justify-content-start"
        style={{
          width: '100%',
          marginTop: '10px',
        }}
      >
        {chargingStationInstances?.map((chargingStationInstance, index) => {
          return (
            <div>
              <Row>
            <Col key={index} xs={6}>
              <Operation
                chargingStationInstance={chargingStationInstance}
                handleRemoveInstance={handleRemoveInstance}
                reconnectChargingStationInstance={() => {
                  reconnectChargingStationInstance(chargingStationInstance);
                }}
              />
            </Col>
           
            </Row>
        </div>
          );
        })}
        
      </Row>
      </Container>
      );
     }

     export async function getChargingStationData() {
     const response = await axios({
     method: 'get',
     url: `${envURL}/getChargingStation`,
   } );
   return response;
   }

根据station_id获取和显示device_id 我尝试添加新组件并将 prop 传递给 Parent(Home) 组件,但无法过滤 根据station_id选择device_id数据。需要同时选择station_id和device_id 选择。 getChargingStationData() -> API 同时具有station_id和device_id数据

ReactJS 节点.js

评论


答: 暂无答案