gpt4 book ai didi

javascript - 在 React 中加载外部脚本(使用 load-script)

转载 作者:行者123 更新时间:2023-12-01 02:38:26 24 4
gpt4 key购买 nike

这段代码是一个简单的重新实现react-coin-hive ,基本上我想了解这里发生了什么。

它加载 Coinhive 的 javascript ,但是我收到错误

Line 8:  'CoinHive' is not defined  no-undef

这是 react 代码:

import React, {Component} from 'react';
import loadScript from 'load-script';

class App extends Component {
buildMiner = async () => {
this.miner = await new Promise(resolve => {
loadScript('https://coinhive.com/lib/coinhive.min.js', () => {
return resolve(CoinHive.Anonymous('WshUK1rGzM29IvlWo1qFhk37IgLIh3t3'));
})
})
};

async componentWillMount() {
this.buildMiner();
this.miner.start();
}

render() {
return (
<div>
Start mining!
</div>
);
}
}

export default App;

如果您正常加载 Coinhive,您将有权访问该对象,并会调用:

<script src="https://coinhive.com/lib/coinhive.min.js"></script>

<script>
var miner = new CoinHive.Anonymous('YOUR_SITE_KEY');
miner.start();
</script>

我的另一个小问题是为什么使用语法:

buildMiner = async () => {}

而不是说:

async buildMiner() {}

最佳答案

我建议您在 componentDidMount 中加载 Coinhive 库,因为这是最佳实践: Reference ,并引用本网站的内容:

If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

React 就是 propsstate ,为什么不从初始化 state 开始呢?在构造函数中,像这样?

  constructor(props) {
super(props);
this.state = {
loadScriptCalled: false, // state variable to let us know if loadScript has run
miner: null // state variable to let us know if the miner is available
};
}

此外,由于您的 buildMiner函数返回 Promise ,您无需调用async然后await “ promise ”你的职能。

  buildMiner = () => {
return new Promise((resolve, reject) => {
loadScript('https://coinhive.com/lib/coinhive.min.js',
(error, script) => {
if (error) {
reject(error);
} else {
console.log("Loaded")
return resolve(CoinHive.Anonymous('WshUK1rGzM29IvlWo1qFhk37IgLIh3t3'));
}
})
})
};

然后,this.buildMinerPromise ,你只需要这样对待它,然后处理你的 state then() 中的组件或catch() block ,像这样:

  componentDidMount() {
this.buildMiner()
.then((miner) => {
console.log("miner :", miner);
this.setState({
loadScriptCalled: true,
miner: miner
});
this.state.miner.start();
})
.catch((error) => {
this.setState({
loadScriptCalled: true
})
console.log("Failed to load CoinHive :", error);
});
}

完整代码可在此处获取:https://codesandbox.io/s/o4lo1my0ky

希望这有帮助!

关于javascript - 在 React 中加载外部脚本(使用 load-script),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47729398/

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