如何在reactjs中使用for循环发送数据以获取Flask中的请求

问题描述

我在烧瓶渲染index.html中实现了多个网络摄像头流。我想使用react框架做同样的事情,但不知道如何做。我尝试使用下面的App.js中所示的for循环,但是它似乎起作用了,我无法找到正确的方法

这是index.html:

<!doctype html>
<html lang="en">
<head>
    <!-- required Meta tags -->
    <Meta charset="utf-8">
    <Meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
          integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <title>Multiple Live Streaming</title>
</head>
<body>
<div class="container">
    <div class="row">

        <div class="col-lg-7">
            <h3 class="mt-5">Multiple Live Streaming</h3>
            {%for i in range(0,2)%}
                <img src="{{ url_for('stream',id=i) }}" width="50%">
            {%endfor%}
        </div>


    </div>
</div>
</body>
</html>

这是烧瓶中的app.py:

from flask import Flask,Response
import cv2
import threading
app = Flask(__name__)

lock = threading.Lock()

@app.route('/stream/<string:id>',methods = ['GET'])
def stream(id):
      return Response(generate(id),mimetype = "multipart/x-mixed-replace; boundary=frame")
   

def find_camera(id):
    cameras = [0,1]
    return cameras[int(id)]

def generate(camera_id):

   global lock
   cam = find_camera(camera_id)
   vc = cv2.VideoCapture(cam)
   
   if vc.isOpened():
      rval,frame = vc.read()
   else:
      rval = False

   
   while rval:
      # wait until the lock is acquired
      with lock:
        
         rval,frame = vc.read()
         
         if frame is None:
            continue

         (flag,encodedImage) = cv2.imencode(".jpg",frame)

         # ensure the frame was successfully encoded
         if not flag:
            continue

      
      yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytearray(encodedImage) + b'\r\n')
   
   vc.release()

if __name__ == '__main__':
   host = "127.0.0.1"
   port = 8000
   debug = False
   options = None
   app.run(host,port,debug,options)

这是app.js,我要在其中实现与index.html中实现的相同:

import React from 'react';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        {%for i in range(0,2)%}
          <img src={'/stream/{i}'} className="App-logo" alt="logo" />

      </header>
    </div>
  );
}

export default App;

任何帮助将不胜感激。

解决方法

您可以尝试

import React from 'react';
import './App.css';

function App() {

  const imageArray = []
  for( let i= 0;i < numberOfSream ;i ++ ) imageArray.push( <img src={'/stream/{id}'} className="App-logo" alt="logo" /> )

  return (
    <div className="App">
      <header className="App-header">
        
          {  imageArray }

      </header>
    </div>
  );
}

export default App;