【问题标题】:JS expression not working as part of a string in ReactJS?JS 表达式不能作为 ReactJS 中字符串的一部分工作?
【发布时间】:2018-04-05 07:12:44
【问题描述】:

你能帮忙吗?

我正在尝试执行以下操作……

import {chosenIpAddress} from './socketEvents.js';

const socket = socketClient(`http:// ${chosenIpAddress} :8081`);

...但无论我尝试什么,它都会忽略我的表情并将其视为http://:8081。我试过用加号、逗号、反引号、引号、喊叫和威胁它,但无济于事。

我可以注销 IP 地址,所以我知道它已被填充,但作为字符串的一部分,它会被忽略,这让我发疯!

提前谢谢xxx

P.S...我见过一些类似的问题,但这些对我的问题没有帮助,因此提出了新问题。

更新:根据要求,这是我的出口......

let chosenIpAddress = "";

function  chosenTank(tank) {
    socket.emit('chosen tank', tank);
    console.log('Tank', tank);
    chosenIpAddress = tank.IpAddress;
}

export {
    chosenIpAddress,
};

【问题讨论】:

  • 你的socketEvents.js是什么?
  • 它是设备之间 'emit' 和 'on' 事件的中介。
  • 只是为了确定,您正在导出它,对吗?
  • 哈哈,是的。我可以在此处通过控制台将其注销,但作为字符串的一部分,它会被忽略。
  • chosenTank 永远不会被调用,所以你导出 { chosenIpAddress: "" }

标签: javascript reactjs


【解决方案1】:

你需要导出一个调用时返回IP地址的函数。

导入chosenIpAddress 的文件具有原始值(空字符串),但即使调用chosenTake 也永远不会更新。 Javascript 字符串是按值复制的,因此如果您更新原始变量,对它的任何其他引用都不会更新

按值复制的字符串示例:

chosenIpAddress = "";
x = chosenIpAddress; // x is ""
chosenIpAddress = "localhost"; // chosenIpAddress is "localhost", x is still ""
// This same issues applies to imports/exports.

所以在你的 ip 地址文件中做这样的事情:

let chosenIpAddress = "";

function chosenTank(tank) {
    socket.emit('chosen tank', tank);
    console.log('Tank', tank);
    chosenIpAddress = tank.IpAddress;
}

function getChosenIpAddress() {
    // This can be "" if chosenTank is not called first
    return chosenIpAddress;
}

export {
    getChosenIpAddress,
};

另外,正如 cmets 中所指出的,您需要在访问 chosenIpAddress 之前调用 chosenTank,否则您每次都会得到一个空字符串。

此外,您还需要将套接字字符串构建为函数,以便在调用时从 getChosenIpAddress 获取最新值:

import {getChosenIpAddress} from './socketEvents.js';

function getChosenSocket() {
    return socketClient(`http://${getChosenIpAddress()}:8081`);
}

【讨论】:

  • 还是一样。选择后注销,但仍作为字符串的一部分被忽略。
  • 您也需要将字符串构建为函数
  • 不,请参阅我的解决方案。
【解决方案2】:

因此,对于遇到此问题的任何人,我都解决了。给出的答案有点接近那里,但不正确,我尝试过(和它的变体),但它/它们没有用。

基本上在我的例子中,IP 地址是在应用程序启动时设置的,所以 chosenIpAddress 总是一个空字符串,因为它是在连接发生之前设置的,没有导出的变化、召回或功能构建就可以完成这项工作。

为了解决这个问题,我使用“占位符”socketClient 进行初始连接,以防止应用程序崩溃...

let socket = socketClient('http://:8081');

...然后,当组件从前端挂载时,我调用以重新填充 IP 地址...

准备就绪时从前端调用...

componentDidMount() {
    frontEndConnected();
}

根据需要添加 IP 地址...

function frontEndConnected() {
    socket = socketClient(`http://${chosenTankIpAddress}:8081`);
}

...很有魅力。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 2011-11-05
    相关资源
    最近更新 更多