简体   繁体   English

如何将 MySQL 查询结果从 Electron “主”进程传回渲染器?

[英]How do I pass MySQL query results back to renderer from Electron "main" process?

I'm building a React/Electron/MySQL app and am trying to pass the results of my query (in ipcMain) back to the renderer.我正在构建一个 React/Electron/MySQL 应用程序,并试图将我的查询结果(在 ipcMain 中)传递回渲染器。 Here is the basic skeleton:这是基本框架:

main.js主程序

ipcMain.handle("testQuery", async (event) => {
  connection.connect(function(err) {
    if(err){throw(err)}
    let sql = "SELECT * FROM `workers`";
    connection.query(sql, function(err, rows, fields) {
      if(err){console.log(err); return}
      console.log("results =", rows);
      connection.end(function(){})
      return rows; // i know this isn't currently returning anywhere useful
    })
  })
})

preload.js预加载.js

contextBridge.exposeInMainWorld("electronAPI", {
  testQuery: () => ipcRenderer.invoke("testQuery").then((result) => {return result})
})

MyComponent.jsx我的组件.jsx

async function testQuery() {
  return await window.electronAPI.testQuery()
}

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {data : "nothing"}
  }

  render() {
    return (
      <button type="button" id="testButton" onClick={() =>
        testQuery((result) => {
          this.setState({data : result})
        })}>Test Query</button>
      <p>{this.state.data}</p>
    )
  }
}

I've tried some approaches found in other threads, like passing a callback through (which didn't work, somewhere the callback got lost).我已经尝试了一些在其他线程中发现的方法,比如传递一个回调(这没有用,回调丢失了)。 I've also received errors like "object could not be cloned" after getting creative moving things around.在创造性地移动事物之后,我也收到了诸如“无法克隆对象”之类的错误。 If I try to declare a variable in the top scope of ipcMain, and pass the query result to it before passing it back as the "invoke" reply, I get "Cannot enqueue Query after invoking quit."如果我尝试在 ipcMain 的顶部 scope 中声明一个变量,并在将查询结果作为“调用”回复传回之前将查询结果传递给它,我会得到“调用退出后无法排队查询”。 What approach should I be aiming towards?我应该瞄准什么方法? (I'm new to working with Promises, as well.) (我也是 Promises 的新手。)

I don't have an easy way to test this, but this is how I would adjust your code.我没有简单的方法来测试它,但这就是我调整代码的方式。 I would also do as midnight-coding suggests and read into callbacks vs promises, serialization, etc. Ultimately, you weren't that far off though, Also.我也会按照午夜编码的建议去做,并阅读回调与承诺、序列化等。最终,你并没有那么遥远,还有。 I assume the rows arg is an array or objects and has serializable data within it, If it does not.我假设行 arg 是一个数组或对象,并且其中包含可序列化的数据,如果没有的话。 you should process that prior to resolving the promise with that data.您应该在使用该数据解析 promise 之前对其进行处理。 Hope this is helpful and best of luck to you!希望这对您有所帮助,祝您好运!

// main.js
ipcMain.handle("testQuery", 
  (event) => new Promise((resolve, reject) => {
      connection.connect(function(err) {
        if(err){
          reject(err); 
        } else {
          const sql = "SELECT * FROM `workers`";
          connection.query(sql, function(err, rows, fields) {
            if(err){
              console.log(err); 
              reject(err);
            } else {              
              console.log({rows});
              connection.end(function(){});
              resolve(rows); 
            }
          })
        }
      })
    })
)
// preload.js
contextBridge.exposeInMainWorld("electronAPI", {
  testQuery: () => ipcRenderer.invoke("testQuery")
})
// mycomponent.jsx
class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {data : "nothing"};
    this.onClick = this.onClick.bind(this);
  }

  async onClick() {
    try {
      const data = await window.electronAPI.testQuery();
      this.setState({data})
    } catch (error) {
      // handle error
    }            
  }

  render() {
    return (
      <button type="button" id="testButton" onClick={this.onClick}>Test Query</button>
      <p>{this.state.data}</p>
    )
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM