withRouter和connect()导致应用崩溃

时间:2018-09-05 05:32:44

标签: reactjs redux react-redux react-router

我正在尝试使用withRouter,以便一旦用户注册后就可以推向历史记录以重定向用户。在我决定实现react-redux之类之前,它一直是完美的。我将connect()HOC添加到了Login组件,现在该应用程序无法加载,就像将withRouter()放入Register组件中一样。我已经尝试过

withRouter(connect(...)(MyComponent))

但不起作用。我无所适从。

Register.js

import React from "react";
import "./Register.css";
import { withRouter } from 'react-router';
const initialUser = {
  username: "",
  email: "",
  password: "",
  password2: "",
  name: ""
};

class Register extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: initialUser,
      registered: ""
    };
  }

  handleChange = event => {
    this.setState({
      user: {
        ...this.state.user,
        [event.target.name]: event.target.value
      }
    });
  };


  isRegistered = () => {
    const { registered } = this.state;
    if (registered) {
      this.props.context.history.push('/path')
    }
  };

  onRegister = event => {
    event.preventDefault();
    fetch("http://localhost:3000/register", {
      method: "post",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(this.state.user)
    })
      .then(res => res.json())
      .then(data => {
        if (data.isRegistered) {
          this.setState({ registered: true });
          this.isRegistered();
        }
      });
  };

  render() {
    return (
      <div className="login-page">
        <div className="form">
          <form className="login-form" onSubmit={this.onRegister}>
            <input
              type="text"
              placeholder="name"
              name="name"
              value={this.state.user.name}
              onChange={this.handleChange}
            />
            <input
              type="text"
              placeholder="username"
              name="username"
              value={this.state.user.username}
              onChange={this.handleChange}
            />
            <input
              type="text"
              placeholder="email"
              name="email"
              value={this.state.user.email}
              onChange={this.handleChange}
            />
            <input
              type="password"
              placeholder="password"
              name="password"
              value={this.state.user.password}
              onChange={this.handleChange}
            />
            <input
              type="password"
              placeholder="confirm password"
              name="password2"
              value={this.state.user.password2}
              onChange={this.handleChange}
            />
            <button className="bluecolor" type="submit">
              Register
            </button>
            <p className="message">
              Have an account? <a href="/login">Login</a>
            </p>
          </form>
        </div>
      </div>
    );
  }
}

export default withRouter(Register);

Login.js

import React from "react";
import { connect } from 'react-redux';
import { setUserStatus } from '../../../actions'

const mapStateToProps = state => {
  console.log('mapstate', state.isLoggedIn)
  return {
    isLoggedIn: state.isLoggedIn
  }
}
const mapDispatchToProps = (dispatch) => {
  return {
    onLoggedInSuccess: () => dispatch(setUserStatus(true))
  }
} 

const initialUser = {
  username: "",
  password: "",
};

class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: initialUser,
      loggedIn: false
    };
  }

  handleChange = event => {
    this.setState({
      user: {
        ...this.state.user,
        [event.target.name]: event.target.value
      }
    });
  };
  onLoginClick = () => {
    const { loggedIn } = this.state;
    console.log(loggedIn, 'this.state')
    if (loggedIn) {
      this.props.onLoggedInSuccess(true);
    }
  };
  onLogin = event => {
    event.preventDefault();
    fetch("http://localhost:3000/login", {
      method: "post",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(this.state.user)
    })
      .then(res => res.json())
      .then(data => {
        if (data.loggedIn) {
          this.setState({ loggedIn: true });
          this.onLoginClick();
        }
      });
  };

  render() {
    return (
      <div className="login-page">
        <div className="form">
          <form className="login-form" onSubmit={this.onLogin}>
            <input
              type="text"
              placeholder="username"
              name="username"
              value={this.state.user.username}
              onChange={this.handleChange}
            />
            <input
              type="password"
              placeholder="password"
              name="password"
              value={this.state.user.password}
              onChange={this.handleChange}
            />
            <button className="bluecolor" type="submit">
              Login
            </button>
            <p className="message">
              Have an account? <a href="/login">Login</a>
            </p>
          </form>
        </div>
      </div>
    );
  }
}

export default connect(mapStateToProps,
    mapDispatchToProps)(Login);

App.js

import React, { Component } from 'react';
import RegisterFull from "./Components/Register/RegisterFull";
import LoginFull from "./Components/Login/LoginFull";
import HomeFull from "./Components/Home/HomeFull";
import FullContact from "./Components/Contact/FullContact";
import './App.css';
import './Components/flex.css'
import {BrowserRouter as Router, Route, Switch} from "react-router-dom";
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      signedIn: false
    };
  }
  loginUser = () => {
    this.setState({ signedIn: true });
  };

  render() {
    console.log(this)
    return (
      <Router>
        <Switch>
          <Route exact path="/" component={HomeFull} />
          <Route exact path="/contact" component={FullContact} />
          <Route exact path="/login" component={LoginFull} />
          <Route exact path="/register" component={RegisterFull} />
          <Route exact path="/about" component={HomeFull} />
        </Switch>
      </Router>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:1)

似乎您忘记了在<Router>标签中加上<Provider>标签。

它看起来应该像这样:

const App = ({ store }) => (
  <Provider store={store}>
    <Router>
      <Route path="/" component={HomeFull} />
      <...other routes go here...>
    </Router>
  </Provider>
);

提供程序来自react-redux软件包。

有关更多详细信息,请参见here