首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我无法在React中实现重定向

我无法在React中实现重定向
EN

Stack Overflow用户
提问于 2019-04-17 15:07:50
回答 3查看 26关注 0票数 0

当某些条件返回null或false,但未触发重定向操作时,我希望重定向到主页。

代码语言:javascript
运行
复制
import { Link, Redirect } from "react-router-dom";

if(localStorage.getItem("example") === null || localStorage.getItem("example") === false){
    return <Redirect to="/" />
}

我将这段代码放在一个在OnClickcomponentDidMount()中触发的简单函数中,但它不起作用。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-04-17 15:16:20

您可以使用重定向到主页,这是基于可以通过在onClickHandler或handleSubmit中使用setState更改的重定向标志。

代码语言:javascript
运行
复制
import { Redirect } from "react-router-dom";

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

  handleSubmit () {
    if(localStorage.getItem("example") === null || localStorage.getItem("example") === false){
      return this.setState({ redirect: true });
    }
  }

  render () {
    const { redirect } = this.state;

    if (redirect) {
      return <Redirect to='/'/>;
    }
    return <YourForm/>;
}
票数 1
EN

Stack Overflow用户

发布于 2019-04-17 15:21:58

你需要在render中使用重定向。它是一个React组件,用于呈现用户,然后将用户发送到所需的路径:

代码语言:javascript
运行
复制
import React, { Component } from "react";
import { Route, Switch, Redirect } from "react-router-dom";

class RootPage extends React.Component {
  state = {
    isLoggedOut: false
  };

  onClick = () => {
    this.setState({
      isLoggedOut: true
    });
  };

  render() {
    return (
      <div>
        {this.state.isLoggedOut && <Redirect to="/logout" />}
        <button onClick={this.onClick}>Logout</button>
      </div>
    );
  }
}

const Log = () => <h1>Logout</h1>;

class App extends Component {
  render() {
    return (
      <div>
        <nav className="navbar navbar" />
        <Switch>
          <Route exact path="/" component={RootPage} />
          <Route exact path="/logout" component={Log} />
        </Switch>
      </div>
    );
  }
}
export default App;

当您单击注销按钮时,它会将您重定向到rootPath。

以下是演示:https://codesandbox.io/s/q9v2nrjnx4

票数 1
EN

Stack Overflow用户

发布于 2019-04-17 15:24:27

看看官方文档中的this example吧。

如果使用类组件,<Redirect />应该在render方法中。或者,如果你使用一个函数组件,它应该在它返回的内容中。

示例如下:

代码语言:javascript
运行
复制
import { Component } from 'react';

const PrivateComponent = (props) => {
  return(
    localStorage.getItem("example")
      ? <RandomComponent />
      : <Redirect to="/signin" />
  )
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55721797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档