我正处于 React 的初级阶段。当“登录”变量值以某种方式更改时,我想重新渲染 ReactDom.render()。假设如果登录变量值从 false 变为 true,则 ReactDom.render() 将重新渲染。我怎样才能做到这一点?任何形式的帮助将不胜感激。代码片段在这里-
import React from "react";
import ReactDOM from "react-dom";
import { createBrowserHistory } from "history";
import { Router, Route, Switch, Redirect } from "react-router-dom";
import AuthLayout from "layouts/Auth.js";
import RtlLayout from "layouts/RTL.js";
import AdminLayout from "layouts/Admin.js";
import "assets/scss/material-dashboard-pro-react.scss?v=1.9.0";
import { Component } from 'react'
import AdminLogin from "views/Signup-Login/AdminLogin";
let loggedin = false
class Index extends Component {
constructor(props) {
super(props)
this.state = {
isLoggedin: false
}
}
LoginStatusHandler = (isLoggedinValue) =>{
alert(isLoggedinValue);
this.setState({
isLoggedin: isLoggedinValue
})
loggedin = isLoggedinValue;
}
render() {
const {isLoggedin} = this.state
return (
<div>
{(() => {
if (isLoggedin === false) {
return <AdminLogin LoginStatusChange={this.LoginStatusHandler}/>;
}
})()}
</div>
)
}
}
//export default Index
const hist = createBrowserHistory();
ReactDOM.render(
<Router history={hist}>
{console.log(loggedin)}
{loggedin?
<Switch>
<Route path="/rtl" component={RtlLayout} />
<Route path="/auth" component={AuthLayout} />
<Route path="/admin" component={AdminLayout} />
<Redirect from="/" to="/admin/dashboard" />
</Switch> : <Index />}
</Router>,
document.getElementById("root")
);
答案 0 :(得分:0)
import React, { Component } from 'react'
import { createBrowserHistory } from "history";
import { Router, Route, Switch, Redirect } from "react-router-dom";
import AuthLayout from "layouts/Auth.js";
import RtlLayout from "layouts/RTL.js";
import AdminLayout from "layouts/Admin.js";
import "assets/scss/material-dashboard-pro-react.scss?v=1.9.0";
import AdminLogin from "views/Signup-Login/AdminLogin";
const hist = createBrowserHistory();
class App extends Component {
constructor(props) {
super(props)
this.state = {
isLoggedin: false
}
}
LoginStatusHandler = (isLoggedinValue) =>{
//alert(isLoggedinValue);
this.setState({
isLoggedin: isLoggedinValue
})
}
render() {
const {isLoggedin} = this.state
return (
<div>
{
isLoggedin === false ?
<AdminLogin LoginStatusChange={this.LoginStatusHandler}/>
:
(<Router history={hist}>
<Switch>
<Route path="/rtl" component={RtlLayout} />
<Route path="/auth" component={AuthLayout} />
<Route path="/admin" component={AdminLayout} />
<Redirect from="/" to="/admin/dashboard" />
</Switch>
</Router>)
}
</div>
)
}
}
export default App