gpt4 book ai didi

javascript - JS 表达式不能作为 ReactJS 中字符串的一部分工作?

转载 作者:行者123 更新时间:2023-11-30 08:23:32 25 4
gpt4 key购买 nike

你能帮忙做点什么吗?

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

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,
};

最佳答案

您需要导出一个在调用时返回 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,
};

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

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

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

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

关于javascript - JS 表达式不能作为 ReactJS 中字符串的一部分工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49614920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com