React路由器(v4)不重定向在componentDidUpdate()

我试图如果用户登录触发重定向。成功的登录触发此this.state.user的更新,所以我想处理重定向在componentDidUpdate()或另一个生命周期方法中。React路由器(v4)不重定向在componentDidUpdate()

当我打算这样做时,if语句会被调用,但重定向什么也不做。任何想法如何我可以解决这个问题?我只是想要更新网址,所以它不一定需要使用重定向。

我目前没有使用用户认证,也不打算添加它。

import React, { Component } from "react"; 

import "./App.css";

import { BrowserRouter as Router, Route, Redirect } from "react-router-dom";

import AuthContainer from "./components/AuthContainer";

import ChatSelector from "./components/ChatSelector";

import { debug } from "util";

// import ChatRoomContainer from './components/ChatRoomContainer';

class App extends Component {

constructor(props) {

super(props);

this.state = {

user: {}

};

}

setUser = user => {

console.log("setting user");

this.setState({ user });

};

componentDidUpdate() {

// if a user is logged in, redirect them to chat-selector

if (Object.keys(this.state.user).length > 0) {

console.log(this.state.user);

<Router>

<Redirect to="/chat-selector" />;

</Router>;

}

}

render() {

return (

<Router>

<div>

<Route

exact

path="/"

render={props => (

<AuthContainer {...props} setUser={this.setUser} />

)}

/>

<Route

exact

path="/chat-selector"

render={props => <ChatSelector {...props} user={this.state.user} />}

/>

{/* <Route exact path='/chatroom' component={ChatRoomContainer}/> */}

</div>

</Router>

);

}

}

export default App;

回答:

我通过将内作出的if语句,并添加重定向布尔州解决了这个。

import React, { Component } from "react"; 

import "./App.css";

import {

BrowserRouter as Router,

Route,

Redirect,

withRouter

} from "react-router-dom";

import AuthContainer from "./components/AuthContainer";

import ChatSelector from "./components/ChatSelector";

import { debug } from "util";

// import ChatRoomContainer from './components/ChatRoomContainer';

class App extends Component {

constructor(props) {

super(props);

this.state = {

user: {},

redirect: false

};

}

setUser = user => {

console.log("setting user");

this.setState({ user });

};

redirect =() => {

this.setState({ redirect: true });

};

render() {

if (

Object.keys(this.state.user).length > 0 &&

this.state.redirect === true

) {

this.setState({ redirect: false });

console.log("logged in");

return (

<Router>

<Redirect to="/chat-selector" />

</Router>

);

} else {

console.log("not logged in");

}

return (

<Router>

<div>

<Route

exact

path="/"

render={props => (

<AuthContainer

{...props}

setUser={this.setUser}

redirect={this.redirect}

/>

)}

/>

<Route

exact

path="/chat-selector"

render={props => <ChatSelector {...props} user={this.state.user} />}

/>

{/* <Route exact path='/chatroom' component={ChatRoomContainer}/> */}

</div>

</Router>

);

}

}

export default App;

以上是 React路由器(v4)不重定向在componentDidUpdate() 的全部内容, 来源链接: utcz.com/qa/259852.html

回到顶部