javascript - 安装组件时导入的脚本不会加载 - React JS

标签 javascript reactjs import

我正在开发一个 React JS 应用程序。我有三个主要的路由,分别是/login/register/app。在应用程序组件中,我导入了一个 swipe.js 脚本,该脚本仅适用于 /app 组件,其余组件则不需要。但是当我运行该应用程序时,它也会自动加载 /login/register 上的脚本,这是第一个问题。第二个问题是,当我登录或注册时,我编写了一个脚本来重定向到 /app 组件,并且成功完成,但是作为 swipe.js已加载,swipe.js 中的事件函数/app上不起作用。不知道是什么问题。

Index.js 代码

import React from 'react';
import ReactDOM from 'react-dom';
//Styles
import './Components/assets/css/bootstrap.css'
//Scripts
import 'bootstrap'
//Components
import App from './App';
import Register from './Components/register'
import Login from './Components/login'
//Routing
import { Route, BrowserRouter as Router } from 'react-router-dom';



ReactDOM.render(
    <Router>
        <Route path={'/app'} component={App} />
        <Route path={'/login'} component={Login} />
        <Route path={'/register'} component={Register} />
    </Router>
    , document.getElementById('root'));

App.js -/app

import React, {Component} from 'react';
//Scripts
import 'bootstrap'
import 'popper.js'
//Custom Scripts
import './Components/assets/js/swipe.min'

// Components
import Navigation from './Components/navigation'
import SideBar from './Components/sidebar'
import Chat from './Components/chat'
import Compose from './Components/compose-modal'


export class App extends Component {
	constructor(props) {
		super(props)
	
		this.state = {
			 
		}
	}

componentDidMount(){
		console.log("App Component Mounted...");
	}
	
	render() {
		return (
			<div className="layout">
				<Navigation />
				<SideBar />
				<Chat />
				<Compose />
			</div>
		)
	}
}

export default App;

登录和注册组件

import React, { Component } from 'react'
import './assets/css/bootstrap.css'
import './scss/auth.scss'
import AuthImage from './assets/img/chat-bg.jpg'
import Profile from './assets/img/avatars/avatar-male-1.jpg'
import { Link, Redirect } from 'react-router-dom';


import {app,  Cookies} from '../Shared/Globals'

export class register extends Component {
    constructor(props) {
        super(props)
    
        this.state = {
             fname:'',
             lname:'',
             email:'',
             pass:'',
             pass2:'',
             formValid : false,
             regFormBtn : 'Join Now',
             formError : {
                 error : false,
                 data : null
             }, 
             registered : false
        }

        this.handleRegisterForm = this.handleRegisterForm.bind(this)
        this.registerUser = this.registerUser.bind(this)
    }


    handleRegisterForm(event){
        this.setState({
            [event.target.name]:event.target.value
        })
        if(this.state.fname !== '' &&
           this.state.lname !== '' &&
           this.state.email !== '' &&
           this.state.pass  !== '' &&
           this.state.pass2 !== '' 
          ){
            this.setState({
                formValid : true
            })
          } else{
            this.setState({
                formValid : false
            })
          }
    }

    registerUser(event){
        event.preventDefault();
        
        if(this.state.formValid){
            this.setState({
                regFormBtn : 'Joining ...',
                formValid : false
            })
            app.auth().createUserWithEmailAndPassword(this.state.email, this.state.pass)
            .then( res => {
                console.log(res);
                new Cookies().createCookie("uid", res.user.uid, '10 minutes');
                this.setState({
                    regFormBtn : 'Success !'
                })
                this.resetForm();
                this.setState({
                    registered : true
                })
            })
            .catch( error =>{
                console.log(error);
                this.setState({
                    formValid : true,
                    regFormBtn : 'Try Again'
                })
                let err = {...this.state}
                err.formError.error = true
                this.setState({
                    err
                })
                switch(error.code){
                    case 'auth/email-already-in-use':
                    case 'auth/weak-password':
                    case 'auth/network-request-failed':
                        {
                            let err = {...this.state}
                            err.formError.data = error.message
                            this.setState({
                                err
                            })
                            break;
                        } 
                        default:
                }
            })
        } else{
            console.log("Form is invalid");
        }

    }
    
    
    render() {
        let e = '';
        if(this.state.formError.error){
           e =  <div className='error'>{this.state.formError.data}</div>
        } else{ e = '' }
        if(this.state.registered){
            return <Redirect to='/app' />
        }
        return (
            <>
                <div className='container auth-row'>
                    <div className='row'>
                        <div className='col-6'>
                            <div className='auth-img'>
                                <img src={AuthImage} alt='auth' />
                            </div>
                        </div>

                        <div className='col-6' >
            <div className='auth'>
                <div className='auth-head'> Join Our Chat Community Now !</div>
                <div className='auth-form'>

                    <form className='row' method='POST' onSubmit={this.registerUser}>
                        <div className='col-12'> {e} </div>
                        <div className='rcaInput col-6'>
                            <input type='text' placeholder='First Name' name='fname' onChange={this.handleRegisterForm} />
                        </div>
                        <div className='rcaInput col-6'>
                            <input type='text' placeholder='Last Name' name='lname' onChange={this.handleRegisterForm} />
                        </div>
                        <div className='rcaInput col-12'>
                            <input type='email' placeholder='Email Address' name='email' onChange={this.handleRegisterForm} />
                        </div>
                        <div className='rcaInput col-12'>
                            <input type='Password' placeholder='Password' name='pass' onChange={this.handleRegisterForm} />
                        </div>
                        <div className='rcaInput col-12'>
                            <input type='Password' placeholder='Repeat Password' name='pass2' onChange={this.handleRegisterForm} />
                        </div>
                        <div className='btn-space col-12'>
                            <button className='rcaBtn' type='submit' disabled={!this.state.formValid}> {this.state.regFormBtn} </button>
                            <div className='small-font' style={{paddingTop:'10px'}}> Already have an account ? <Link to={'/login'} > Login Now</Link> </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

                    </div>
                </div>
            </>
        )
    }
}

export default register 

最佳答案

在app.js文件中你可以稍微修改它:

let swipe;

export class App extends Component {
  constructor(props) {
    super(props)

    this.state = { swipeLoaded: false };
  }

  componentDidMount() {
    swipe = require('./...swipe.js'); // require your swipe file here
    this.state = { swipeLoaded: true };
  }
}

为了防止渲染中出现其他问题(因为在 CDM 中设置状态会导致重新渲染),请将其添加到 render() 中:

if (!this.state.swipeLoaded) return null;

关于javascript - 安装组件时导入的脚本不会加载 - React JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56930552/

相关文章:

javascript - 文本内容对比insideText 跨浏览器解决方案

javascript - 为子组件的每个实例传递两个不同的数据列表?

mysql - 如何加快数据加载到 InnoDB (LOAD DATA INFILE)?

database - 如何使用mongoimport导入csv

javascript - 如何选择单个 div 并在 jquery 中独立于其他元素对其及其相关元素进行动画处理

javascript - 使用 Function 构造函数创建的函数始终在全局范围内创建

javascript - 在 css 中使用圆形 div mask 动画

javascript - 如何更有效地在组件之间传递状态和属性

javascript - 从子组件函数更新 React 状态

java - 导入通配符是否始终导入所有内容?