首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在React应用程序开始时运行脚本?

如何在React应用程序开始时运行脚本?
EN

Stack Overflow用户
提问于 2018-11-15 21:02:04
回答 1查看 59关注 0票数 0

我认为这是一个简单的问题,但我不清楚最好的方法。

除了运行我的React App之外,我还需要异步且独立地运行一个脚本,以便(例如)将用户指纹添加到我的数据库中。

此脚本的结果不会影响应用程序,但我需要在App中包含此脚本,因为我正在使用App函数。

我可以想到两种方法:

1) index.js内部

代码语言:javascript
复制
import { add_fingerprint }  from './utils/Functions';
add_fingerprint();

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

2)在App组件内部:

代码语言:javascript
复制
import { add_fingerprint }  from './utils/Functions';

class App extends Component {

  constructor(props) {
    super(props)    
  }

  componentDidMount(){
    add_fingerprint();
  }

  render () {
    return (<div>My app</div>)
  }

}

add_fingerprint函数:

代码语言:javascript
复制
export function add_fingerprint () {

  import axios from 'axios';
  import Fingerprint2 from 'fingerprintjs2';

  setTimeout(function () {
    Fingerprint2.get(function (components) {
    //axios call to add to my database         
    })  
  }, 500)

}

最正确的方法是什么?

EN

回答 1

Stack Overflow用户

发布于 2018-11-15 21:18:05

第二点是正确的。

如果需要从远程端点加载数据,这是实例化网络请求的好地方。https://reactjs.org/docs/react-component.html#componentdidmount

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53320086

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档