反应路由器正在改变URL,但不正确加载网页(React router is changing the

2019-10-28 16:43发布

我工作的一个阵营JS项目,该项目内,我使用做出反应路由器V4创建一个客户端路线。

这是项目现场网址: https://gokhana.herokuapp.com/

在主页上,客户将搜索城市/位置(仅适用于印度城市),只要客户将选择位置( https://prnt.sc/jsy8rp ),我要加载的下一个路由,即https://开头gokhana .herokuapp.com /餐厅 。

我使用<Redirect />的页面重定向到/restaurants路线。

/restaurants路线被加载时,页面没有加载正确,一切都搞砸。 检查这个它是如何加载https://prnt.sc/jsy96i

现在,如果我重新加载相同的URL,在页面加载正确没有任何问题https://prnt.sc/jsya4t

重定向到与路线<Redirect />产生了一个问题,而重装同一路线工作正常。

我已经检查了CSS和JS文件全部都是正常加载。

我无法弄清楚这个问题。

app.js文件

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import store from './store';

import $ from 'jquery';
import 'bootstrap/dist/css/bootstrap.min.css';

import Routers from './routes/AppRouter';

//Import CSS files
import './styles/google-font.css';
import './styles/base.css';

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

index.html文件

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>GoKhana</title>
        <link rel="icon" type="image/png" href="./images/favicon.png">
        <link rel="stylesheet" type="text/css" href="./dist/styles.css">
    </head>
    <body>
        <div id="root"></div>


        <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
        <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCmnIFpWp5ofkwDLZgCDLBat1VPEjOj_jA&libraries=places"></script>            
        <script src="./dist/bundle.js"></script>

        <script src="./js/common_scripts_min.js"></script>
        <script src="./js/functions.js"></script>
        <script src="./js/modernizr.js"></script>

        <script  src="./js/cat_nav_mobile.js"></script>
        <script>$('#cat_nav').mobileMenu();</script>
        <script src="./js/ion.rangeSlider.js"></script>
        <script src="./js/cat_nav_mobile.js"></script>
        <script src="./js/theia-sticky-sidebar.js"></script>

        <script src="./js/bootstrap3-wysihtml5.min.js"></script>
        <script src="./js/dropzone.min.js"></script>
        <script src="./js/tabs.js"></script>

        <script src="./js/custom.js"></script>
    </body>
</html>

AppRouter.js文件

import React from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';

import HomePage from './../components/HomePage';
import AboutUs from './../components/AboutUs';
import ContactUs from './../components/ContactUs';
import PageNotFound from './../components/PageNotFound';
import RestaurantList from '../components/RestaurantList';
import RestaurantMenu from '../components/RestaurantMenu';
import UserDetails from '../components/UserDetails';
import OrderConfirmation from '../components/OrderConfirmation';
import CustomerAccount from '../components/CustomerAccount';

export default () => {
    return (
        <BrowserRouter>
            <Switch>
                <Route path="/" component={HomePage} exact={true}/>
                <Route path="/about" component={AboutUs} />
                <Route path="/contact" component={ContactUs} />
                <Route path="/restaurants" component={RestaurantList} />
                <Route path="/select-menu" component={RestaurantMenu} />
                <Route path="/user-details" component={UserDetails} />
                <Route path="/order-confirmation" component={OrderConfirmation} />
                <Route path="/my-account" component={CustomerAccount} />
                <Route component={PageNotFound} />
            </Switch>
        </BrowserRouter>
    );
}

RestaurantList.js -该组件是乱七八糟

import React from 'react';

import Header from './sections/Header';
import Footer from './sections/Footer';
import ImageSubHeader from './sections/ImageSubHeader';
import Filters from './sections/Filters';
import DisplayRestaurants from './sections/DisplayRestaurants';

export default () => {
    return (
        <div>
            <Header />
            <ImageSubHeader title="Search your Favorite Restaurant" showSearch = "true" /> 

            <div className="container margin_60_35">
                <div className="row">
                    <Filters />
                    <DisplayRestaurants />
                </div>
            </div>

            <Footer />
        </div>
    );
}

ImageSubHeader.js

    import React from 'react';

    import subHeaderImg from './../../images/web-images/mainbanner.jpg';

    export default (props) => {
        return (
            <section className="parallax-window" id="short" data-parallax="scroll" data-image-src={subHeaderImg} data-natural-width="1400" data-natural-height="350">
                <div id="subheader">
                    <div id="sub_content">
                        <h1>{props.title}</h1>
                        <p>{props.subTitle}</p>
                        {props.showSearch && 
                            (<form method="post" action="list_page.html">
                                <div id="custom-search-input">
                                    <div className="input-group ">
                                        <input type="text" className=" search-query" placeholder="Your Address or postal code" />
                                        <span className="input-group-btn">
                                        <input type="submit" className="btn_search" value="submit" />
                                        </span>
                                    </div>
                                </div>
                            </form>)
                        }

                        {props.showOrder && 
                            (
                                <div className="bs-wizard">
                                    <div className={(props.orderId >=1) ? "col-xs-4 bs-wizard-step complete" : "col-xs-4 bs-wizard-step disabled"}>
                                        <div className="text-center bs-wizard-stepnum"><strong>1.</strong> Your details</div>
                                        <div className="progress"><div className="progress-bar"></div></div>
                                        <a href="#0" className="bs-wizard-dot"></a>
                                    </div>

                                    <div className={(props.orderId >=2) ? "col-xs-4 bs-wizard-step complete" : "col-xs-4 bs-wizard-step disabled"}>
                                        <div className="text-center bs-wizard-stepnum"><strong>2.</strong> Payment</div>
                                        <div className="progress"><div className="progress-bar"></div></div>
                                        <a href="cart_2.html" className="bs-wizard-dot"></a>
                                    </div>

                                    <div className={(props.orderId >=3) ? "col-xs-4 bs-wizard-step complete" : "col-xs-4 bs-wizard-step disabled"}>
                                        <div className="text-center bs-wizard-stepnum"><strong>3.</strong> Finish!</div>
                                        <div className="progress"><div className="progress-bar"></div></div>
                                        <a href="cart_3.html" className="bs-wizard-dot"></a>
                                    </div>  
                                </div>
                            )
                        }
                    </div>
                </div>
            </section>
        );
    }

Filters.js

import React from 'react';

export default () => {
    return (
        <div className="col-md-3">
            <div id="filters_col">
                <a 
                    data-toggle="collapse" 
                    href="#collapseFilters" 
                    aria-expanded="false" 
                    aria-controls="collapseFilters" 
                    id="filters_col_bt
                "> 
                Filters 
                    <i className="icon-plus-1 pull-right"></i>
                </a>

                <div className="collapse" id="collapseFilters">
                    <div className="filter_type">
                        <h6>Distance</h6>
                        <input type="text" id="range" value="" name="range" />
                        <h6>Type</h6>
                        <ul>
                            <li><label><input type="checkbox" checked className="icheck" />All <small>(49)</small></label></li>
                            <li><label><input type="checkbox" className="icheck" />American <small>(12)</small></label><i className="color_1"></i></li>
                            <li><label><input type="checkbox" className="icheck" />Chinese <small>(5)</small></label><i className="color_2"></i></li>
                            <li><label><input type="checkbox" className="icheck" />Hamburger <small>(7)</small></label><i className="color_3"></i></li>
                            <li><label><input type="checkbox" className="icheck" />Fish <small>(1)</small></label><i className="color_4"></i></li>
                            <li><label><input type="checkbox" className="icheck" />Mexican <small>(49)</small></label><i className="color_5"></i></li>
                            <li><label><input type="checkbox" className="icheck" />Pizza <small>(22)</small></label><i className="color_6"></i></li>
                            <li><label><input type="checkbox" className="icheck" />Sushi <small>(43)</small></label><i className="color_7"></i></li>
                        </ul>
                    </div>
                    <div className="filter_type">
                        <h6>Rating</h6>
                        <ul>
                            <li><label><input type="checkbox" className="icheck" /><span className="rating">
                            <i className="icon_star voted"></i><i className="icon_star voted"></i><i className="icon_star voted"></i><i className="icon_star voted"></i><i className="icon_star voted"></i>
                            </span></label></li>
                            <li><label><input type="checkbox" className="icheck" /><span className="rating">
                            <i className="icon_star voted"></i><i className="icon_star voted"></i><i className="icon_star voted"></i><i className="icon_star voted"></i><i className="icon_star"></i>
                            </span></label></li>
                            <li><label><input type="checkbox" className="icheck" /><span className="rating">
                            <i className="icon_star voted"></i><i className="icon_star voted"></i><i className="icon_star voted"></i><i className="icon_star"></i><i className="icon_star"></i>
                            </span></label></li>
                            <li><label><input type="checkbox" className="icheck" /><span className="rating">
                            <i className="icon_star voted"></i><i className="icon_star voted"></i><i className="icon_star"></i><i className="icon_star"></i><i className="icon_star"></i>
                            </span></label></li>
                            <li><label><input type="checkbox" className="icheck" /><span className="rating">
                            <i className="icon_star voted"></i><i className="icon_star"></i><i className="icon_star"></i><i className="icon_star"></i><i className="icon_star"></i>
                            </span></label></li>
                        </ul>
                    </div>
                    <div className="filter_type">
                        <h6>Options</h6>
                        <ul className="nomargin">
                            <li><label><input type="checkbox" className="icheck" />Delivery</label></li>
                            <li><label><input type="checkbox" className="icheck" />Take Away</label></li>
                            <li><label><input type="checkbox" className="icheck" />Distance 10Km</label></li>
                            <li><label><input type="checkbox" className="icheck" />Distance 5Km</label></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    );
}

DisplayRestaurants.js

import React from 'react';
import GridListRestaurant from './GridListRestaurant';

export default () => {
    return (
        <div className="col-md-9">
            <div id="tools">
                <div className="row">
                    <div className="col-md-3 col-sm-3 col-xs-6">
                        <div className="styled-select">
                            <select name="sort_rating" id="sort_rating">
                                <option value="" selected>Sort by ranking</option>
                                <option value="lower">Lowest ranking</option>
                                <option value="higher">Highest ranking</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <GridListRestaurant />
            <GridListRestaurant />

        </div>
    );
}

重定向逻辑SearchLocationBar.js

import React from 'react';
import {connect} from 'react-redux';
import {Redirect} from 'react-router-dom';

import {setLocation} from './../../actions/locationActions';
import {toggleLoader} from './../../actions/loaderActions';

class SearchLocationBar extends React.Component {
    location = {}
    state = {
        redirect : false
    }

    componentDidMount() {
        let autocomplete = document.getElementById('autocomplete');
        let GoogleMapsApi = new google.maps.places.Autocomplete((autocomplete), {
            types: '(regions)',
            componentRestrictions: {country: 'in'}
        });

        google.maps.event.addListener(GoogleMapsApi, 'place_changed', () => {
            this.location = {};
            const place = GoogleMapsApi.getPlace();
            this.location.latitude = place.geometry.location.lat();
            this.location.longitude = place.geometry.location.lng();

            place.address_components.forEach((address) => {
                if(address.types.includes('locality')) {
                    this.location.city = address.long_name;
                } else if(address.types.includes('administrative_area_level_2')) {
                    this.location.city = address.long_name;
                } else if(address.types.includes('administrative_area_level_1')) {
                    this.location.state = address.long_name;
                }

            });
            this.props.setLocation(this.location);
            localStorage.setItem('location',JSON.stringify(this.location));

            this.setState({redirect: true});
        });

    }
    render() {
        return (
            <form autoComplete="off" method="post">
                <div id="custom-search-input">
                    <div className="input-group ">
                        <input 
                            type="text" 
                            className=" search-query" 
                            placeholder="Your Address or postal code"
                            id="autocomplete"
                        />
                        {this.state.redirect ? <Redirect to='/restaurants' /> : ''}
                        <span className="input-group-btn">
                        <input type="submit" className="btn_search" value="submit" />
                        </span>
                    </div>
                </div>
            </form>
        );
    }
}

const mapStateToProps = (state) => {
    return state;
};

const mapDispatchToProps = {
    setLocation,
    toggleLoader
};

export default connect(mapStateToProps, mapDispatchToProps)(SearchLocationBar);

Answer 1:

大量的研究后,我找到了答案,我的问题。

在路由器做出反应,如果我们重定向到新的路线,然后JS库不加载。 就我而言,我是用它被注入HTML元素的网页加载完成后的插件。

现在,作出反应,这里的一切是虚拟的DOM路由不会加载页面,所以这里的解决方案是路由完成后加载JS库。

所以我用loadjs包。

1)安装

yarn add loadjs

2)进口

import loadjs from 'loadjs';

3)在阵营组分componentDidMount()调用它

loadjs('./js/modernizr.js', () => {});

这将解决此问题。



文章来源: React router is changing the URL but not loading the webpage properly