1

这些是我的类和组件:

应用程序.js:

import { connect } from "react-redux";
import Main from "./components/main/Main";
import * as actions from "./redux/actions";
import { bindActionCreators } from "redux";
import { withRouter } from "react-router";

function mapStateToProps(state) {
  console.log(state);

  return {
    // naming must be exact same as function in reducer
    auth: state.auth,
    errorBag: state.errorBag
  };
}
function mapDispatchProps(dispatch) {
  return bindActionCreators(actions, dispatch);
}
const App = withRouter(connect(mapStateToProps, mapDispatchProps)(Main));
export default App;

主.js:

import React, { Component } from "react";
import { Redirect } from "react-router";
import { Route } from "react-router-dom";
import Login from "./../login/Login";
import Home from "./../home/Home";

class Main extends Component {

  render() {

    return (
      <div>
        <Route
          path="/login"
          render={param => {
            return <Login {...this.props} {...param} />;
          }}
        />

        {!this.auth ? <Redirect to="/login" /> : <Home />}
      </div>
    );
  }
}

export default Main;

减速器.js:

import { combineReducers } from "redux";

function authenticateReducer(state = null, action) {
  switch (action.type) {
    case "AUTHENTICATE": {
      return action.token;
    }
    default: {
      return state;
    }
  }
}
function errorBagReducer(state = [], action) {
  switch (action.type) {
    case "ADD_ERROR": {


      console.log("called");

      return { [action.area]: action.error };
    }
    default:
      return state;
  }
}

const rootReducer = combineReducers({ authenticateReducer, errorBagReducer });
export default rootReducer;

动作.js:

import axios from "axios";

export function startSignUp(signUpData) {
  return dispatch => {

    return axios
      .post("http://localhost:8000/api/v1/user/sign-up/", signUpData)
      .then(res => {
        console.log(res);
        authenticate(res.data.shaba);
      })
      .catch(error => {
        console.log(error.data);
      });
  };
}
export function addErrorIntoBag(area, error) {
  return {
    type: "ADD_ERROR",
    area,
    error
  };
}


function authenticate(token) {
  return {
    type: "AUTHENTICATE",
    token
  };
}

登录.js:

import React, { Component } from "react";
import "./login.css";
import InlineAlert from "./../alerts/InlineAlert";

class Login extends Component {
  constructor(props) {
    super(props);
  }
  getAreaName = () => "LOGIN";
  submitHandler = event => {
    event.preventDefault();
    const email = event.target.elements.email.value;
    const code = event.target.elements.code.value;
    const password = event.target.elements.password.value;
    if (password === "" || code === "" || email === "") {
      this.props.addErrorIntoBag(this.getAreaName(), "fill the form please");

      return;
    }
    const data = {
      email: email,
      password: password,
      national_code: code
    };
    this.props.startSignUp(data);
    this.forceUpdate();
  };
  render() {
    return (
      <div id="parent" onSubmit={this.submitHandler}>
        <form id="form_login">
          <h2>Login</h2>
          <br />
          <div className="form-group">
            <label forhtml="exampleInputEmail1">National code</label>
            <input
              key="code"
              type="text"
              className="form-control"
              id="exampleInputEmail1"
              aria-describedby="emailHelp"
              name="code"
            ></input>
          </div>
          <div className="form-group">
            <label forhtml="exampleInputPassword1">Email</label>
            <input
              type="email"
              className="form-control"
              id="email"
              name="email"
              key="email"
            ></input>
          </div>
          <div className="form-group">
            <label forhtml="exampleInputPassword1">Password</label>
            <input
              type="password"
              className="form-control"
              id="name"
              name="password"
              key="password"
            ></input>
          </div>
          <div className="form-group form-check"></div>
          <button type="submit" className="btn btn-light">
            SIGN-UP
          </button>
        </form>
        {/* drill down checking   */}
        {this.props.errorBag && this.props.errorBag[this.getAreaName()] && (
          <InlineAlert error={this.props.errorBag[this.getAreaName()]} />
        )}
      </div>
    );
  }
}

export default Login;

当我调用并且表单为空时submitHandlerLogin.js它会调用一个操作来更改 redux 存储并且Login.js组件必须更新并且InlieAlert组件必须出现在屏幕上,但是任何东西都不会改变!

是因为我的Main.js那是登录和 Redux 的中间吗?

我很困惑!

4

1 回答 1

2

dispatch我猜你忘了调用startSignUp函数。authenticate像你一样从对象返回是不够的,你{ type: "AUTHENTICATE", token }还需要传递给dispatch。通过这种方式,您正在触发状态更改。

从以下文档dispatch(action)

调度一个动作。这是触发状态更改的唯一方法。

也许您可以尝试以某种方式执行以下操作:

export function startSignUp(signUpData) {
  return dispatch => {
    return axios
      .post("http://localhost:8000/api/v1/user/sign-up/", signUpData)
      .then(res => {
        console.log(res);
        // missing dispatch added
        dispatch(authenticate(res.data.shaba));
      })
      .catch(error => {
        console.log(error.data);
      });
  };
}

因此,您可以考虑在状态更改的最后调用如下:

dispatch({
  type: "AUTHENTICATE",
  token
});

我希望这有帮助!

于 2020-01-01T17:48:51.377 回答