dispatch 在 React Redux 中无法用于身份验证

问题描述 投票:0回答:2

我调用

register
,函数执行了,但它的内部
dispatch
函数没有执行,.

注册

import React, { Component } from "react";
import { Link, Navigate } from 'react-router-dom'; 
import { connect } from 'react-redux';
import { register } from '../actions/auth'

class Register extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: '',
      re_password: '',
      accountCreated: false
    }
  }

  onSubmit(e) {
    e.preventDefault();

    let { username, password, re_password } = this.state
    if (password === re_password) {
      register(username, password, re_password); <-- here

      this.setState({ accountCreated: true });
    }
  }

  render() {
    if (this.state.accountCreated) {
      return <Navigate to='/' />
    }

    return (
      <div className="container mt-5">
        <h1>Register for an Account</h1>
        <p>Create an account with our Session Auth application</p>
        <form onSubmit={(e) => this.onSubmit(e)}>
          <div className="form-group">
            <label htmlFor="username" className="form-label">
              Username: 
            </label>
            <input
              type="text"
              className="form-control"
              placeholder="Username*"
              name='username'
              value={this.state.username}
              onChange={(e) => this.setState({ username: e.target.value })} 
              required
            />
          </div>
          <div className="form-group">
            <label htmlFor="password" className="form-label">
              Password:
            </label>
            <input
              type="password"
              className="form-control"
              placeholder="Password*"
              name='password'
              value={this.state.password}
              onChange={(e) => this.setState({ password: e.target.value })} 
              minLength={6}
              required
            />          
          </div>
          <div className="form-group">
            <label htmlFor="confirm_password" className="form-label">
              Confirm Passeord:
            </label>
            <input
              type="password"
              className="form-control"
              placeholder="Confirm Password*"
              name='re_password'
              value={this.state.re_password}
              onChange={(e) => this.setState({ re_password: e.target.value })} 
              minLength={6}
              required
            />
          </div>
          <button className="btn btn-primary mt-3" type="submit">Register</button>
        </form>
        <p className="mt-3">
          Already have an Account? <Link to='/login'>Sign In</Link>
        </p>
      </div>
    )
  }
}

export default connect(null, { register })(Register); <-- here

文件操作/身份验证

import axios from 'axios';
import {
  REGISTER_SUCCESS,
  REGISTER_FAIL
} from './types';
import Cookies from 'js-cookie';

const URL = `${process.env.REACT_APP_API_URL}`;

export const register = (username, password, re_password) => async dispatch => {
  const csrftoken = Cookies.get('csrftoken');
  const config = {
    headers: {
      'Accept': 'application/json',
      'Content-Type' : 'application/json',
      // 'Cache-Control' : 'no-cache'
      'X-CSRFToken' : csrftoken
    }
  };

  const body = JSON.stringify({ username, password, re_password });

  try { 
    const res = await axios
      .post(URL + '/accounts/register', body, config)
      .catch((err) => console.log(err));
        
    if (res.data.error) {
      dispatch({
        type : REGISTER_FAIL
      });
    } else {
      dispatch({
        type : REGISTER_SUCCESS
      });
    }
  } catch (err) {
    dispatch({
      type : REGISTER_FAIL
    });
  }
};

文件缩减器/身份验证

import {
  REGISTER_SUCCESS,
  REGISTER_FAIL
} from '../actions/types';

const initilState = {
  isAthenticated: null,
  username: '',
  first_name: '',
  last_name: '',
  phone: '',
  city: ''
};

export default function(state = initilState, action) {
  const { type, payload } = action;

  switch(type) {
    case REGISTER_SUCCESS:
      return {
        ...state,
        isAthenticated: false
      }

    case REGISTER_FAIL:
      return state

    default:
      return state
  }
};

dispatch
必须执行,信息会发送到服务器并确定类型。

javascript reactjs redux redux-thunk dispatch
2个回答
0
投票

要执行调度,您可以使用如下方法传递调度对象

register(username,password,re_password, dispatch);

或者您可以在调用此方法时获得响应,然后在那里执行检查并按如下方式调度

register(username,password,re_password).then(res=>
        if (res.data.error){
            dispatch({
                type : REGISTER_FAIL
            });
        } else {
            dispatch({
                type : REGISTER_SUCCESS
            });
        }
)

0
投票

connect
高阶组件注入选择的状态和可分派动作作为props到它正在装饰的组件中。在您的代码中,您直接调用
register
操作创建者,而不是 not 调用
dispatch
的调用中包含并作为 prop 注入的版本。

import React, { Component } from "react";
import { Link, Navigate } from 'react-router-dom'; 
import { connect } from 'react-redux';
import { register } from '../actions/auth'; // <-- register #1

class Register extends Component {
  ...

  onSubmit(e) {
    e.preventDefault();

    const { username, password, re_password } = this.state;
    if (password === re_password) {
      register(username, password, re_password); // <-- calling register #1

      this.setState({ accountCreated: true });
    }
  }

  ...
}

export default connect(null, { register })(Register); // <-- register #2

您应该调用作为 props 注入到

register
组件中的
Register

import React, { Component } from "react";
import { Link, Navigate } from 'react-router-dom'; 
import { connect } from 'react-redux';
import { register } from '../actions/auth'; // <-- register #1

class Register extends Component {
  ...

  onSubmit(e) {
    e.preventDefault();

    const { username, password, re_password } = this.state;
    if (password === re_password) {
      this.props.register(username, password, re_password); // <-- calling register #2

      this.setState({ accountCreated: true });
    }
  }

  ...
}

export default connect(null, { register })(Register); // <-- register #2
© www.soinside.com 2019 - 2024. All rights reserved.