ReactJS: including script in a specific component

2019-08-09 06:38发布

问题:

I need to include jquery and form validations libraries into a specific component. I have already tried react-async-script-loader but couldn't get it to work.

Please note, I am using the Laravel and ReactJS. Also the code I have included is the sample code from the github repository (https://github.com/leozdgao/react-async-script-loader). However, I have the downloaded files to used in the Laravel public folder.

Here is the error I am getting:

Uncaught TypeError: Cannot convert undefined or null to object
at Function.getOwnPropertyNames (<anonymous>)
at hoistNonReactStatics (app.js:50805)
at app.js:50617
at Module../resources/js/components/TorrentsAdd.jsx (app.js:81726)
at __webpack_require__ (app.js:20)
at Module../resources/js/Index.js (app.js:81096)
at __webpack_require__ (app.js:20)
at Object../resources/js/app.js (app.js:81203)
at __webpack_require__ (app.js:20)
at Object.0 (app.js:82191)

Here is the code:

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import Axios from 'axios';
import scriptLoader from 'react-async-script-loader';

/** elements */
import Breadcrumbs from './elements/Breadcrumbs';

export default scriptLoader(
    [
        'https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js',
        'https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.5/marked.min.js'
    ]
)(SampleForm)

class SampleForm extends Component
{
    constructor()
    {
        super();

        this.state = {
            categories: [],
            years: [],
            status: [],
        };
    }

    componentWillReceiveProps({ isScriptLoaded, isScriptLoadSucceed })
    {
        if (isScriptLoaded && !this.props.isScriptLoaded) // load finished
        { 
            if (isScriptLoadSucceed)
            {
                this.initEditor()
            }
            else
            {
                this.props.onError()
            }
        }
    }

    componentDidMount()
    {
        const { isScriptLoaded, isScriptLoadSucceed } = this.props;

        if (isScriptLoaded && isScriptLoadSucceed)
        {
            this.initEditor()
        }
    }

    componentWillMount()
    {
        Axios
            .get("/api/categoriesDropdown")
            .then(response => {
                this.setState({
                    categories: response.data.categories,
                    years: response.data.years,
                    status: response.data.status
                });
            });
    }

    render()
    {
        ...
    }
}