React JS外部脚本加载

时间:2018-03-16 16:56:57

标签: javascript reactjs router

我在React中构建了一个在线图库,它需要一个外部脚本才能正常工作。

有两个主要组件,即Home.js和Single.js。 Home.js显示图像组织的一些类别,Single.js是类别的详细视图(它包含特定类别下的所有照片)。路由器看起来像这样:

    <Provider store={ store }>
        <Router
            forceRefresh={ false }>
            <div id="router">
                <Switch>
                    <Route exact path='/' render={ () => <MainLayout><Home /></MainLayout> } />
                    <Route exact path='/about' render={ () => <MainLayout><About /></MainLayout> } />
                    <Route path='/single/:id' render={ (props) => <MainLayout><Single {...props} /></MainLayout> } />
                </Switch>
            </div>
        </Router>
    </Provider> 

我正在加载脚本&#39; main.js&#39;使用此功能:

appendScripts() {
    const main = document.createElement('script');
    main.src = '/js/main.js';
    main.async = true;
    main.id = 'main';
    document.body.appendChild(main);
}

现在的问题是脚本在Home.js组件上加载,但是只有在第二次通过主页访问它时,它才会加载到Single.js组件上(对于同一类别),即使它附加在DOM中。通过Single.js访问主页同样如此。如果首先加载Single.js,我需要通过Single.js访问Home.js 2次,以便正确加载脚本。

组件都具有以下功能:

    componentDidMount() {
        this.appendScripts();
    }

    componentWillMount() {
        this.props.getImages(this.state.id);
        this.props.getCategory(this.state.id);
    }

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

我的猜测是,由于ReactRouter实际上并没有刷新页面,因此脚本正在缓存,只是第二次出现而没有运行。我会把脚本放到一个函数中然后在其他地方调用它,可能在componentDidMount中,或者至少在加载脚本时注册一个监听器并运行它。

答案 1 :(得分:0)

我有一个与您相似的用例,它是按需加载Google Recaptcha的。确保脚本在呈现访问外部脚本的组件之前已加载的关键思想。这是一个简单的例子

  1. 创建一个名为loading
  2. 的状态
  3. componentDidMount,附加脚本标记,设置onload回调并设置src。
  4. 脚本加载后会调用onload到setState({loading:false})
  5. 进行条件渲染{!loading && from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext from numpy import get_include from os import system # compile the fortran modules without linking fortran_mod_comp = 'gfortran fortfunction.f90 -c -o fortfunction.o -fPIC' print fortran_mod_comp system(fortran_mod_comp) shared_obj_comp = 'gfortran fortinterface.f90 -c -o fortinterface.o -fPIC' print shared_obj_comp system(shared_obj_comp) # needed if building with NumPy : this includes the NumPy headers when compiling. path_includes = [get_include()] ext_modules = [Extension('m', # module name: ['m.pyx'], # source file: libraries = ['gfortran'], # need to include gfortran as a library extra_link_args=['fortfunction.o', 'fortinterface.o'])] # other files to link to setup(name = 'm', cmdclass = {'build_ext': build_ext}, include_dirs = path_includes, ext_modules = ext_modules) }

我已经在这里复制了代码https://gist.github.com/kykean/29edc055e75a39bdcd329d3323f8bf0b 该示例使用recompose,并且是HOC,但核心思想是相似的。