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

时间:2017-12-09 14:09:06

标签: javascript reactjs promise

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

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

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

以下是反应代码:

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() {}

1 个答案:

答案 0 :(得分:2)

我建议您在componentDidMount中加载Coinhive库,因为这是最佳做法: Reference,并引用此网站:

  

如果您需要从远程端点加载数据,这是实例化网络请求的好地方。

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致电&#34; promisify&#34;你的功能。

  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,您只需将其视为此处,并在statethen()块中处理catch()组件,像这样:

  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

希望这有帮助!