React-router history.push()已成功更改URL,但未将我的JXS内容重新呈现为具有匹配路径的正确Route内容

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React-router history.push()已成功更改URL,但未将我的JXS内容重新呈现为具有匹配路径的正确Route内容相关的知识,希望对你有一定的参考价值。

  1. 我以前通过呈现整个页面的组件来更改页面,该方式是使用setState“ currentPage:'xxx'”并在内部带有开关盒以匹配正确的参数,以便它可以呈现'xxx'的内容。 >
  2. 这两天,我试图用React-router代替这种旧方法,并且在登录页面和仪表板页面之间发生了这种情况。

我以前放置了一个调用API的提交函数来接收决定是否重新渲染到仪表板页面的结果

但是现在如果我要重新渲染应该显示的内容,它将无法通过Submit函数(至少我不知道如何使用它)>

因此,我将history.push()放入提交函数的API结果中,以便当结果状态为“ true”时,history.push()将被执行。

但是问题发生在这里,即,history.push完全执行,URL已正确更改为localhost:3000 / dashboard,但我的页面完全没有改变。

  1. 我有第二个问题,与我以前的scase-case-render方法相比,使用React-router有什么优势?

    顺便说一下,我使用Create-react-app

  2. 这是我的代码

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import axios from 'axios';
import './dist/css/adminlte.min.css';
import './plugins/fontawesome-free/css/all.min.css';
import './plugins/icheck-bootstrap/icheck-bootstrap.min.css';
import  { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Login from "./Login";
import Board from "./Board";
import { createBrowserHistory } from 'history';

class Ares extends React.Component {
    constructor(props) {
        super(props);
        console.log("reconstructor");
        this.state={
            currentPage:"login",
            currentMainContent:"empty",
            currentNav:"Classic",
            account:'moore_huang@you-ce.net',
            email:'',
            password:'abc123'	,
            sid:'',
            startAt:new Date('1970-01-01 12:00:00'),
            endAt:new Date(),
            access_token:'',
            memberPage:1,
            memberData:[],
            nowPick:'',
        };
    }
    handleChange(event){//每一鍵輸入後觸發 檢查輸入字元
        const target=event.target;
        this.setState({
            [target.name]: target.value
        });
    }
    submitLogin(event){
        event.preventDefault();
        //------------------------------------------------------
        axios.post('/api/login',
            {
                email:this.state.account,
                password:this.state.password
            },
            {
                baseURL:'http://www.localhost.ares.net'
            })
            .then((result) => this.getSidFunc(result.data))
            .catch((error) => { console.error(error) })
    }
    submitLogin2(event){
        event.preventDefault();
        this.setState({
            sid:'Im in',
            currentPage:'home',
        });
    }
    getSidFunc(response){
        if(response.status===1){
            console.log("login success");
            let history=createBrowserHistory();
            // let history = this.props.history;
            history.push("/dashboard",true);
            // this.state.history.push("/dashboard");
            console.log(history);
            // window.location.href=window.location.origin+"/dashboard";
            this.setState({
                sid:'Im in',
                currentPage:'home',
                access_token:response.result.access_token
            });
            console.log("----------------------------");

        }else{
            console.log("login fail");
            alert("wrong account or password");
        }
    }
    postRequest(url, payload, onLoadFunc, onErrorFunc, bRetry){
        var xhr = new XMLHttpRequest();
        xhr.open("POST", url);
        xhr.setRequestHeader('Content-type', 'application/json');
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.onload = function(event)
        {
            var jsonData = null;
            try
            {
                jsonData = JSON.parse(xhr.responseText);
                if (onLoadFunc)
                    onLoadFunc(jsonData);
            }
            catch(e)
            {
                console.log(e);
                console.log("xhr json error    bRetry: " + bRetry + "    data: 
" + xhr.responseText);
                if (bRetry)
                {
                    setTimeout(function()
                    {
                        this.postRequest(url, payload, onLoadFunc, onErrorFunc, bRetry);
                    }, 3000);
                }
            }
        };
        xhr.onerror = function(event)
        {
            console.log("xhr onerror    bRetry: " + bRetry);
            if (onErrorFunc)
                onErrorFunc(event);
            if (bRetry)
            {
                setTimeout(function()
                {
                    this.postRequest(url, payload, onLoadFunc, onErrorFunc, bRetry);
                }, 3000);
            }
        };

        xhr.send(JSON.stringify(payload));
    }


    render() {
        console.log("////////////");
        console.log(this.state);
        return (
            <Router>
                <Switch>
                    <Route exact={true} path="/">
                        <Login
                            submitLogin={(event) => this.submitLogin(event)}
                            submitLogin2={(event) => this.submitLogin2(event)}
                            handleChange={(event) => this.handleChange(event)}
                            account={this.state.account}
                            password={this.state.password}
                        />
                    </Route>
                    <Route exact={true} path="/dashboard">
                        <Board

                        />
                    </Route>
                </Switch>
            </Router>
        );
    }
}
// ========================================

ReactDOM.render(
    <Ares />,
    document.getElementById('root')
);
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable javascript to run this app.</noscript>
    <div id="root"></div>

  </body>
</html>

这里是Login.js

import React from 'react';
import ReactDOM from 'react-dom';
import  { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';

function Login(props) {
    console.log("renderLogin");
    return (
        <div className="hold-transition login-page">
            <div className="login-box">
                <div className="login-logo">
                </div>
                <div className="card">
                    <div className="card-body login-card-body">
                        <p className="login-box-msg">Sign in to start your session</p>
                        <form onSubmit={props.submitLogin}>
                            <div className="input-group mb-3">
                                <input
                                    type="email"
                                    className="form-control"
                                    placeholder="Email"
                                    onChange={props.handleChange}
                                    name={"account"}
                                    value={props.account}
                                />
                                <div className="input-group-append">
                                    <div className="input-group-text">
                                        <span className="fas fa-envelope"></span>
                                    </div>
                                </div>
                            </div>
                            <div className="input-group mb-3">
                                <input
                                    type="password"
                                    className="form-control"
                                    placeholder="Password"
                                    onChange={props.handleChange}
                                    name={"password"}
                                    value={props.password}
                                />
                                <div className="input-group-append">
                                    <div className="input-group-text">
                                        <span className="fas fa-lock"></span>
                                    </div>
                                </div>
                            </div>
                            <div className="row">
                                <div className="col-8">
                                    <div className="icheck-primary">
                                        <input type="checkbox" id="remember"/>
                                        <label htmlFor="remember">
                                            Remember Me
                                        </label>
                                    </div>
                                </div>
                                <div className="col-4">
                                    {/*<Link to='/dashboard'>*/}
                                        <button className="btn btn-primary btn-block">Sign In</button>
                                    {/*</Link>*/}
                                </div>
                            </div>
                        </form>

                        <div className="social-auth-links text-center mb-3">
                            <p>- OR -</p>
                            <a onClick={props.submitLogin2}>
                                <i  className="fab fa-facebook mr-2"></i> Sign in using Facebook
                            </a>
                            <a href="#" className="btn btn-block btn-danger">
                                <i className="fab fa-google-plus mr-2"></i> Sign in using Google+
                            </a>
                        </div>

                        <p className="mb-1">
                            <a href="forgot-password.html">I forgot my password</a>
                        </p>
                        <p className="mb-0">
                            <a href="register.html" className="text-center">Register a new membership</a>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default Login;

我曾经通过呈现整个页面的组件来更改页面,在这种情况下,可以使用setState“ currentPage:'xxx'”并在其内部使用开关盒来匹配正确的参数,以便可以呈现'xxx'...

答案

请在类外部声明历史对象。例如

const history = createBrowserHistory();
另一答案

您应该首先在App.js中定义路线,如下所示:

以上是关于React-router history.push()已成功更改URL,但未将我的JXS内容重新呈现为具有匹配路径的正确Route内容的主要内容,如果未能解决你的问题,请参考以下文章

如果使用 history.push 访问特定路由,React-Router v5 不会重定向

React-router history.push()已成功更改URL,但未将我的JXS内容重新呈现为具有匹配路径的正确Route内容

hash history cannot push state it is ignored

组件不刷新的react-router路由问题

react-router:如何在不导致导航/重新加载的情况下更新 url?

如何在 react-router 中以编程方式进行服务器端路由?