【问题标题】:Code working in separate js file but not in ReactJs app代码在单独的 js 文件中工作,但不在 ReactJs 应用程序中
【发布时间】:2021-06-24 08:47:16
【问题描述】:

我正在使用以下代码从 python 脚本中获取值。当我在单独的文件中运行它时,它可以完美运行:

var spawn = require('child_process').spawn;
const process = spawn('python', ['src/components/BTC_NT.py']);

process.stdout.on('data', data => {
    test = data.toString();
});

process.stderr.on('data', (data) => {
    console.log('err results: %j', data.toString('utf8'))
});
process.stdout.on('end', function(){
    console.log(test);
});

但是当我像这样在我的 React 应用程序中运行它时:

import React from "react";
import { useState } from "react";

const Main = () => {
    const [Text, setText] = useState('');
    const [showPrice, setShowPrice] = useState('');
    const getVal = (e) => {
        e.preventDefault();
        var spawn = require('child_process').spawn;
        const process = spawn('python', ['src/components/BTC_NT.py']);

        process.stdout.on('data', data => {
            test = data.toString();
        });

        process.stderr.on('data', (data) => {
            console.log('err results: %j', data.toString('utf8'))
        });
        process.stdout.on('end', function(){
            console.log(test);
            setShowPrice(test);
        });
    }
    return(
        <div className="Main">
            <p>
                The following cryptocurrencies are available: Bitcoin(BTC), Ethereum(ETH). 
            </p>
            <form onSubmit={getVal}>
                <label htmlFor="CurrencyName">Currency Name: </label>
                <input type="text" className="CurrencyName" value={Text} onChange={(e) => setText(e.target.value)} />
                <button style={{marginLeft:"5px"}} type="submit">Submit</button>
            </form>
            {showPrice !== '' && showPrice}
        </div>
    )
}
export default Main;

我收到错误消息 - “TypeError: spawn is not a function”。

对此的任何帮助将不胜感激。

【问题讨论】:

  • Node-specific JS 不能在浏览器中使用。

标签: javascript node.js reactjs forms


【解决方案1】:

当您在本地运行文件时,您显然正在使用其他一些运行时(可能是 node.js),当您在 react 中运行文件时,您在浏览器中运行它,而 child_process 之类的东西却不见了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-04
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多