【问题标题】:Integrating Flask and ReactJS with the use of jQuery使用 jQuery 集成 Flask 和 ReactJS
【发布时间】:2019-02-21 00:42:55
【问题描述】:

TL;DR:我如何将 jQuery 代码(请参见下文)集成/实现到 ReactJS 中?

大家好。 ReactJS 和 Flask 的业余用户在这里。 我只是在寻找关于如何将 jQuery 代码集成到 ReactJS 的解决方案,或者考虑到生命周期中的实现与 ReactJS 不同的其他替代方案。

目前,这个 sn-p(请参阅下面的样板 jQuery 代码)与 Flask 的 CRUD 操作通信非常好,它以 base64 格式从FileReader() 发送选择的图像,并在以下情况下响应相应的预测(通过 ML 模型) #predict-button 被按下。

<body>
    <input id="image-selector" type="file">
    <button id="predict-button">Predict</button>
    <p style="font-weight:bold">Predictions</p>
    <p>foo1: <span id="foo1"></span></p>
    <p>foo2:   <span id="foo2"></span></p>
    <p>foo3:   <span id="foo3"></span></p>
    <img id="selected-image" src=""/>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<script>
let base64Image;
    $("#image-selector").change(function() {
        let reader = new FileReader();
        reader.onload = function(e) {
            let dataURL = reader.result;
            $('#selected-image').attr("src",dataURL);
            base64Image = dataURL.replace("data:image/jpeg;base64,","");
        }
        reader.readAsDataURL($("#image-selector")[0].files[0]);
        $("#foo1").text("");
        $("#foo2").text("");
        $("#foo3").text("");
    });

    $("#predict-button").click(function(event){
        let message = {
            image: base64Image
        }
        console.log(message);
        $.post("http://127.0.0.1:5000/predict",JSON.stringify(message),function(response){
            $("#foo1").text(response.prediction.foo1.toFixed(6));
            $("#foo2").text(response.prediction.foo2.toFixed(6));
            $("#foo3").text(response.prediction.foo3.toFixed(6));
            console.log(response);
        });
    });
</script>
</body>

更不用说,我不再需要 FileReader() 了,因为我在 ReactJS 的“react-webcam”中有这个函数 captureShot(),它返回当前网络摄像头图像的 base64 编码字符串。

  captureShot = () => {
    const screenshot = this.webcam.getScreenshot();
    this.setState({ imageData: screenshot });

  }

会出现这样的问题:

  1. 这可以在 ReactJS 中实现吗?
  2. 如果是这样,怎么做?是通过ComponentDidMount() 还是在render() 内部?
  3. 如果不是,是否使用 Express 方式在 ReactJS 中执行 CRUD 操作并前往 Flask?

我们将不胜感激任何形式的帮助。非常感谢您的时间和考虑。

【问题讨论】:

    标签: javascript jquery reactjs flask


    【解决方案1】:

    这个问题对于 SO 来说可能过于宽泛,但简短的回答是“是的”,您可以这样做。让你以 React 的方式思考可能是我能提供的最好的答案,而不是为你构建它。

    您的image-selector div 将成为 React 组件。它将有一个 onChange 属性指向一个自定义类方法,您可以在其中执行其余的业务逻辑。您的predict-button 将同样成为一个组件,这次以onClick 作为您的道具。由于您正在运行所有函数作为对操作的响应,因此您不需要 constructorcomponentDidMount 中的任何引导数据。

    您也可以使用本机 fetch 或类似库来替换您的 $.post 调用。最后,您将不再需要任何 jQuery 代码,但如果您将代码逐段转换,您将在此过程中学到很多东西。我建议使用 Create React App 来轻松进入架构。

    【讨论】:

    • 感谢您的回复!那 defo 让我更好地了解从哪里开始。我认为从函数captureShot() 开始是理想的,因为const screenshot = this.webcam.getScreenshot(); 提供了base64 格式,而这正是我现在所需要的。关于摆脱 FileReader() 并将其替换为已捕获的编码图像的任何提示?
    【解决方案2】:

    我问这个奇怪问题的纯粹兴奋肯定让三个反对者感到困惑哈。感谢@jmargolisvt 的善意建议,我已经成功了,我的 Flask 服务器现在终于可以与我的 ReactJS 进行良好的通信了 - 项目完成了!

    这是解决方案,以防万一有人感兴趣。

    export default class App extends Component { 
    constructor(props){
        super(props);
        this.state = {
          bar: { foo1: null, foo2: null, foo3: null },
        }
      }
    
    captureShot = () => {
        const screenshot = this.webcam.getScreenshot();
        let base64Image = screenshot.replace("data:image/jpeg;base64,","");
        this.setState({ 
          imageData: screenshot,
         });
    
        let message = {
          image: base64Image
        }
    
       fetch('http://127.0.0.1:5000/', {
        method: 'post',
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify(message)
        })
      .then((response) => {
        console.log(response);
        return response.json();  
      })
      .then((data) => {
        this.setState( {
          bar: {
            foo1: (data.prediction.foo1.toFixed(3)),
            foo2: (data.prediction.foo2.toFixed(3)),
            foo3: (data.prediction.foo3.toFixed(3)),
          }
        })   
      })
       .catch(error => this.setState({ error,  bar: { foo1: null, foo2: null, foo3: null }, }));
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-02
      • 1970-01-01
      • 2014-11-29
      • 1970-01-01
      • 2016-07-05
      • 2015-06-26
      • 2019-04-24
      • 2018-11-30
      • 1970-01-01
      相关资源
      最近更新 更多