【问题标题】:react shards history.push only appends to url, will not redirectreact shards history.push 只附加到 url,不会重定向
【发布时间】:2019-05-19 22:31:04
【问题描述】:

我有一个注册组件,它有一个表单和一个handleFormSubmit。它调用一个 api 来路由到运行 sequelize create 的服务器。这一切都有效,但是一旦插入该行,我想重定向到某个视图。

目前在promise中插入后,我有一个history.push("/dashboard")。但是,这只是附加到浏览器 url 而不是实际重定向。

这里是注册组件,因此您可以看到表单以及 handleFormSubmit。我只是希望它重定向到“/dashboard”路线:

import React, { Component } from "react";
import PropTypes from "prop-types";
import {
  Card,
  CardHeader,
  ListGroup,
  ListGroupItem,
  Row,
  Col,
  Form,
  FormGroup,
  FormInput,
  FormSelect,
  FormTextarea,
  Button
} from "shards-react";

// GET DATA FROM API (which calls routes from express server)
import API from "../../utils/API";
import Auth from "../../utils/Auth";
import { createHashHistory } from 'history'
export const history = createHashHistory();

class Signup extends Component {
  state = {
  };

  handleInputChange = event => {
    const { id, value } = event.target;
    this.setState({
      [id]: value
    });
  };

  handleFormSubmit = event => { 
    event.preventDefault();
    // console.log("Yo");
      API.addUser({

        firstName: this.state.feFirstName,
        lastName: this.state.feLastName,
        email: this.state.feEmail,
        password: this.state.fePassword,
        address1: this.state.feAddress,
        city: this.state.feCity,
        state: this.state.feInputState,
        zip: this.state.feZipCode,
        description: this.state.feDescription,
        userName: this.state.feEmail,
        imageLink: this.state.feImage,
        title: this.state.feTitle,
        github: this.state.feGithub,
        linkedin: this.state.feLinkedIn,
        phone: "",
        userRating: "1",
        bizRating: "1"

      })
        .then( res =>
          // console.log("Added,apparently");
          {
            // set the token and then redirect to the "/books" route
            // Auth.setToken(res.data.token);
            Auth.setToken(res.data.token);
            // console.log("TOKEN: " , res.data.token);
            console.log(res.data);
            history.push(`/dashboard/`);
          })
        .catch(err => console.log(err));
    // }
  }



  render() {
    return (

    <Card small className="mb-4">
      <CardHeader className="border-bottom">
        <h6 className="m-0">Personal Info</h6>
      </CardHeader>
      <ListGroup flush>
        <ListGroupItem className="p-3">
          <Row>
            <Col>
              <Form>
                <Row form>
                  {/* First Name */}
                  <Col md="6" className="form-group">
                    <label htmlFor="feFirstName">First Name</label>
                    <FormInput
                      id="feFirstName"
                      placeholder="First Name"
                    // value=""
                    onChange={this.handleInputChange}
                    />
                  </Col>
                  {/* Last Name */}
                  <Col md="6" className="form-group">
                    <label htmlFor="feLastName">Last Name</label>
                    <FormInput
                      id="feLastName"
                      placeholder="Last Name"
                    // value=""
                    onChange={this.handleInputChange}
                    />
                  </Col>
                </Row>
                <Row form>
                  {/* Email */}
                  <Col md="6" className="form-group">
                    <label htmlFor="feEmail">Email</label>
                    <FormInput
                      type="email"
                      id="feEmail"
                      placeholder="Email Address"
                    // value=""
                    onChange={this.handleInputChange}
                      autoComplete="email"
                    />
                  </Col>
                  {/* Password */}
                  <Col md="6" className="form-group">
                    <label htmlFor="fePassword">Password</label>
                    <FormInput
                      type="password"
                      id="fePassword"
                      placeholder="Password"
                    // value=""
                    onChange={this.handleInputChange}
                      autoComplete="current-password"
                    />
                  </Col>
                </Row>
                <FormGroup>
                  <label htmlFor="feAddress">Address</label>
                  <FormInput
                    id="feAddress"
                    placeholder="Address"
                    // value=""
                    onChange={this.handleInputChange}
                  />
                </FormGroup>
                <Row form>
                  {/* City */}
                  <Col md="6" className="form-group">
                    <label htmlFor="feCity">City</label>
                    <FormInput
                      id="feCity"
                      placeholder="City"
                    // value=""
                    onChange={this.handleInputChange}
                    />
                  </Col>
                  {/* State */}
                  <Col md="4" className="form-group">
                    <label htmlFor="feInputState">State</label>
                    <FormSelect id="feInputState">
                      <option>Choose...</option>
                      <option>...</option>
                    </FormSelect>
                  </Col>
                  {/* Zip Code */}
                  <Col md="2" className="form-group">
                    <label htmlFor="feZipCode">Zip</label>
                    <FormInput
                      id="feZipCode"
                      placeholder="Zip"
                    // value=""
                    onChange={this.handleInputChange}
                    />
                  </Col>
                </Row>
                <Row form>
                  {/* Title */}
                  <Col md="6" className="form-group">
                    <label htmlFor="feTitle">Title</label>
                    <FormInput
                      id="feTitle"
                      placeholder="Title"
                    // value=""
                    onChange={this.handleInputChange}
                    />
                  </Col>
                  {/* Image */}
                  <Col md="6" className="form-group">
                    <label htmlFor="feImage">Image</label>
                    <FormInput
                      id="feImage"
                      placeholder="Image"
                    // value=""
                    onChange={this.handleInputChange}
                    />
                  </Col>
                </Row>
                <Row form>
                  {/* Github */}
                  <Col md="6" className="form-group">
                    <label htmlFor="feGithub">Github</label>
                    <FormInput
                      id="feGithub"
                      placeholder="Github Profile"
                    // value=""
                    onChange={this.handleInputChange}
                    />
                  </Col>
                  {/* LinkedIn */}
                  <Col md="6" className="form-group">
                    <label htmlFor="feLinkedIn">LinkedIn</label>
                    <FormInput
                      id="feLinkedIn"
                      placeholder="LinkedIn Profile"
                    // value=""
                    onChange={this.handleInputChange}
                    />
                  </Col>
                </Row>
                <Row form>
                  {/* Description */}
                  <Col md="12" className="form-group">
                    <label htmlFor="feDescription">Description</label>
                    <FormTextarea id="feDescription" rows="5"
                      // value=""
                      onChange={this.handleInputChange} 
                      />
                  </Col>
                </Row>
                <Button onClick={this.handleFormSubmit} theme="accent">Add Account</Button>
              </Form>
            </Col>
          </Row>
        </ListGroupItem>
      </ListGroup>
    </Card>
  );
  }
}

export default Signup;

我还要注意,这是分片仪表板模板,所以这是客户端 app.js 的设置方式。

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

import routes from "./routes";
import withTracker from "./withTracker";

import "bootstrap/dist/css/bootstrap.min.css";
import "./styles/shards-dashboards.1.1.0.min.css";

export default () => (
  <Router basename={process.env.REACT_APP_BASENAME || ""}>
    <div>
      {routes.map((route, index) => {
        return (
          <Route
            key={index}
            path={route.path}
            exact={route.exact}
            component={withTracker(props => {
              return (
                <route.layout {...props}>
                  <route.component {...props} />
                </route.layout>
              );
            })}
          />
        );
      })}
    </div>
  </Router>
);

既然如此,它就会像这样引用我的 routes.js。所以我确实设置了路线。

// CUSTOM ROUTES
import Home from "./views/Home";
import Portfolio from "./views/UserPortfolio";
import AddFolio from "./views/PortfolioAdd";
import AddProject from "./views/ProjectAdd";
import Signup from "./views/SignUp";
import Dashboard from "./views/Dashboard";

export default [
  {
    path: "/",
    exact: true,
    layout: DefaultLayout,
    component: () => <Redirect to="/home" />
  },
  {
    path: "/home",
    layout: DefaultLayout,
    component: Home
  },
  {
    path: "/folio",
    layout: DefaultLayout,
    component: Portfolio
  }, 
  {
    path: "/addfolio",
    layout: DefaultLayout,
    component: AddFolio
  },   
  {
    path: "/addproject",
    layout: DefaultLayout,
    component: AddProject
  },   

  // USER ROUTES
  {
    path: "/signup",
    layout: DefaultLayout,
    component: Signup
  }, 
  {
    path: "/dashboard",
    layout: DefaultLayout,
    component: Dashboard
  },  

最后,我只想看到一个重定向到承诺中的任何路线,对我来说哪一个都没关系。就这样我看到它起作用了。

所以请让我知道需要提供哪些信息,因为我不确定每个人对分片实现的熟悉程度,因为它显然与标准的反应路线设置有所不同。我确定我遗漏了一些信息。谢谢大家!

【问题讨论】:

  • 您已经创建了一个hash 历史记录。推送不是类似于#/dashboard 吗?
  • 您需要使用withRouter 访问历史对象,而不是直接导入它。官方文档网站可以在 withRouter 上为您提供帮助,因为您已经在使用 BrowserRouter
  • 是的,你是对的。我将其更改为: import { createBrowserHistory } from 'history' export const history = createBrowserHistory();现在它会正确填充地址栏中的 url。例如,在本地提交后,它确实将 url 正确设置为“localhost:3000/dashboard”,但实际上从未重定向。
  • 要重定向你必须使用withRouter。在官方文档中阅读它。

标签: reactjs web-components-shards


【解决方案1】:

Panther 是正确的,需要在 withRouter 中封装组件

在组件上添加: import { withRouter } from 'react-router-dom'; 然后“用Router(whateverClassName)导出默认值;”在底部

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-15
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 2021-02-20
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多