Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

javascript - Initialstate not updated after success login

I just learned how react-redux works.

I created a backend with express js and used axios in the fronted(authentication). After I login, it just gives me a success status.but I can't understand why after success login the state still like initialState in reducer login.js

 
import React,{ useState} from 'react'
import { connect, useDispatch } from 'react-redux'
import {login} from '../../actions/authentication'
import './auth.css' 
import LoginForm from './LoginForm'
import {Link} from 'react-router-dom'

const Login = ({history, login}) => {

     const dispatch = useDispatch();
     const [formData, setFormData] = useState({
       email: "",
       password:""
     });

     const hundleChange = (e) => {
       setFormData({ ...formData, [e.target.name]: e.target.value })

     }

     const hundleSubmit = (e) => {
       e.preventDefault();
       dispatch(login(formData));
       history.push("/");
     }
    return(
      <div>
        <div className="forms">
          <h2>Login</h2>
          <LoginForm   email = {formData.email}
            password = {formData.password}
            hundleSubmit = {hundleSubmit}
            hundleChange = {hundleChange}/>
        </div>
        <p>Do you not have account</p>
         <Link to="/register">Sign Up</Link>
      </div>
    )
  }

const mapStateToProps = state => (
  {
  
     auth : state.auth
}
)
export default connect (mapStateToProps, {login})(Login);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found the solution,the problem was with the import import {LOGIN_USER_SUCCESS} from '../actions/types'

import axios from 'axios'
import {LOGIN_USER_SUCCESS} from '../actions/types'

//login user
export const login = (formData) => async (dispatch) =>{
    //formData ={email, password}
    try {
     const res =  await axios.post("/api/auth/login", formData)
     dispatch({
         type: LOGIN_USER_SUCCESS,
         payload: res.data
     });
     console.log("here data", dispatch.payload)

    } catch (error) {
        console.dir(error);
        const response = error.response.data;
        if(Array.isArray(response)){
            response.forEach((err) =>
            {
                alert(err.msg);
            });
        }
        dispatch({
            type: AUTH_FAILURE
        });
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...