使用react

时间:2019-03-20 13:50:22

标签: ajax reactjs

如果成功的数据具有特定值,我想重定向到组件。 当ajax返回数据时,取决于重定向到我先前导入的Contents类的数据值。 我一直在寻找有关push方法的信息 我的错误是:Error: Invariant failed: You should not use <Redirect> outside a <Router>

 import React, { Component } from 'react';
    import { Modal,Button } from 'react-bootstrap';
    import $ from 'jquery'; 
    import {  Redirect } from 'react-router';
    import Contents from './Contents';
    class Login extends Component {
        constructor(props, context) {
            super(props, context);

            this.handleShow = this.handleShow.bind(this);
            this.handleClose = this.handleClose.bind(this);
            this.handleloginClick = this.handleloginClick.bind(this);
            this.handleUsernameChange = this.handleUsernameChange.bind(this);
            this.handlePasswordChange = this.handlePasswordChange.bind(this);

            this.state = {
              show: true,
              username: "",
              password: "",
            };
          }

          handleloginClick(event) {
          var parametros = {
            username: this.state.username,
            password: this.state.password
          }
          const { history } = this.props;

          $.ajax({
            data: parametros,
            url: "https://privada.mgsehijos.es/react/login.php",
            type: "POST",
            success: function (data) {
               }
          });   
      }

      handleUsernameChange(event) {
            this.setState({username: event.target.value});
        }

        handlePasswordChange(event) {
          this.setState({password: event.target.value});
      }
        handleClose() {
        this.setState({ show: false });
      }

      handleShow() {
        this.setState({ show: true });
      }

         render() {


    If(Condicion){     
         return (<Redirect to={'./Contents'} />);
       }
 return (
          //Here my modal.
     );
              }
          }
          export default Login;

2 个答案:

答案 0 :(得分:0)

有两种方法可以解决此问题。如果您使用的是DECLARE @tbl1 TABLE ( CodeRaw INT, Serial_Raw INT, Qty INT) DECLARE @tbl2 TABLE ( CodeBatch INT, CodeRaw INT, Serial_Raw INT, QtyAdded INT) INSERT INTO @tbl1 VALUES(1,1,100) INSERT INTO @tbl1 VALUES(1,2,150) INSERT INTO @tbl1 VALUES(2,1,80) INSERT INTO @tbl1 VALUES(1,3,100) INSERT INTO @tbl2 VALUES(1,1,1,80) INSERT INTO @tbl2 VALUES(2,1,1,10) INSERT INTO @tbl2 VALUES(3,1,2,150) INSERT INTO @tbl2 VALUES(4,1,3,80) --Inner table has the summary of the Quantity added with columns CodeRaw and SerialRaw. Outer table make join with inner table and just substruct with the Qty and Sum of Qty Added. SELECT t2.Serial_Raw, t1.Qty - t2.QtyAdded AS Total_Remaining FROM @tbl1 t1 INNER JOIN (SELECT CodeRaw, Serial_Raw , SUM(QtyAdded) QtyAdded FROM @tbl2 GROUP BY CodeRaw, Serial_Raw) AS t2 ON t2.CodeRaw = t1.CodeRaw AND t1.Serial_Raw = t2.Serial_Raw WHERE t1.Qty - t2.QtyAdded > 0 包,则只需导入特殊组件react-router并进行渲染即可:

<Redirect>

或者甚至使用特殊的render(){ if(condition) return (<Redirect to='/' />) } prop

history
  

要使用componentDidMount(){ this.props.history.push('/') } ,您的组件必须使用HOC this.props.history

生成

这里是detailed answer

答案 1 :(得分:0)

您可以使用Router dom进行导航。

我的小提琴:https://jsfiddle.net/leolima/fLnh9z50/1/

const AboutUs = (props) => {

  console.log(props.location.state)
  console.log('Hi, you are in About page, redirecting with router dom in 3 seconds')

  setTimeout(() => {
  console.log('foi');
  props.history.push('/')}, 3000);

  return <h1>Now we're here at the about us page.</h1>;
};

完整示例:

// Select the node we wish to mount our React application to
const MOUNT_NODE = document.querySelector('#app');

// Grab components out of the ReactRouterDOM that we will be using
const { BrowserRouter, Route, Switch, NavLink, Link } = window.ReactRouterDOM;

// PropTypes is used for typechecking
const PropTypes = window.PropTypes;

// Home page component
const Home = () => {
  return <h1>Here we are at the home page.</h1>;
};

// AboutUs page component
const AboutUs = (props) => {

  console.log(props.location.state)

  return <h1>Now we're here at the about us page.</h1>;
};

// NotFoundPage component
// props.match.url contains the current url route
const NotFoundPage = ({ match }) => {
    const {url} = match;

    return (
    <div>
      <h1>Whoops!</h1>
      <p><strong>{url.replace('/','')}</strong> could not be located.</p>
    </div>
    );
};


// Header component is our page title and navigation menu
const Header = () => {
    // This is just needed to set the Home route to active 
  // in jsFiddle based on the URI location. Ignore.
    const checkActive = (match, location) => {
    if(!location) return false;
    const {pathname} = location;

    return pathname.indexOf('/tophergates') !== -1 || pathname.indexOf('/_display/') !== -1;
  }

  return (
    <header>
      <h1>Basic React Routing</h1>
      <nav>
        <ul className='navLinks'>
          {/* Your home route path would generally just be '/'' */}
          <li><NavLink to="/tophergates" isActive={checkActive}>Home</NavLink></li>
          <li><Link to={{
            pathname: "/about",
            state: { fromDashboard: true }
          }}>About</Link></li>
        </ul>
      </nav>
    </header>
  );
};


// Out layout component which switches content based on the route
const Layout = ({children}) => {
  return (
    <div>
      <Header />
      <main>{children}</main>
    </div>
  );
};

// Ensure the 'children' prop has a value (required) and the value is an element.
Layout.propTypes = {
  children: PropTypes.element.isRequired,
};

// The top level component is where our routing is taking place.
// We tell the Layout component which component to render based on the current route.
const App = () => {
  return (
    <BrowserRouter>
      <Layout>
        <Switch>
          <Route path='/tophergates' component={Home} />
          <Route path='/_display/' component={Home} />
          <Route exact path='/' component={Home} />
          <Route path='/about' component={AboutUs} />
          <Route path='*' component={NotFoundPage} />
        </Switch>
      </Layout>
    </BrowserRouter>
  );
};

// Render the application
ReactDOM.render(
    <App />, 
  MOUNT_NODE
);