React应用程序被重定向到未指定的路由

问题描述 投票:1回答:1

我是前端开发的新手,我正在努力学习ReactJS。在我的一个示例应用程序中,我使用“live-server public”命令在我的localhost上启动应用程序以进行开发。

package.json的内容

{
  "name": "indecision-app",
  "version": "1.0.0",
  "main": "index.js",
  "author": "Phani Kumar",
  "license": "MIT",
  "dependencies": {
    "babel-preset-env": "1.5.2",
    "babel-preset-react": "6.24.1"
  }
}

我的应用程序正在使用babel编译,并使用live-server自动启动。

"use strict";
var app = {
    title: 'Indecision App',
    subtitle: 'put your life in the hands of a computer',
    options: ['one','two']
};

function showOptions(){
    if (app.options.length > 0){
        return <p>Here are your options</p>
    }else {
        return <p>No Options</p>
    }
}

var template = (
    <div>
        <h1>{app.title}</h1>
        {app.subtitle && <p>{app.subtitle}</p>}
        {showOptions()}
        <ol>
            <li>Item one</li>
            <li>Item two</li>
        </ol>
    </div>
);

var user = {
    name: 'phani',
    age: 30,
    location: 'Bangalore'
};
var userName = 'PhaniKumar Yadavilli';
var age = 30;
var location = "Bangalore";

function getLocation(location){
    if (location){
        return <p>Location: {location}</p>;
    }else {
    return undefined;
    }
}

var templateTwo = (
    <div>
        <h1>{user.name ? user.name : 'Anonymous'}</h1>
        {(user.age && user.age >= 18) && <p>Age: {user.age}</p>}
        {getLocation(user.location)}
    </div>
);
var appRoot = document.getElementById('app');


ReactDOM.render(templateTwo, appRoot);

当我点击URL 127.0.0.1:8080时,应用程序被重定向到127.0.0.1:8080/Bangalore。我试过调试但我无法理解这个重定向的原因是什么。

index.html内容

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf8">
        <title>Indecision App</title>
    </head>
    <body>
        <div id="app"></div>
        <script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
        <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
        <script src="/scripts/app.js"></script>
    </body>
</html>
reactjs babel npm-liveserver
1个回答
2
投票

语句var location = 'Bangalore';触发重定向,因为location是JavaScript中用于表示浏览器URL的保留字。将变量重命名为不同的变量


编辑:正确重定向一个人会这样做:window.location = 'somewhere to go to'

var location = ''更像是一个“虫子”

© www.soinside.com 2019 - 2024. All rights reserved.