【问题标题】:How to update state with redux如何使用 redux 更新状态
【发布时间】:2021-05-20 17:26:30
【问题描述】:

我正在尝试构建简单的登录表单(来自 API 的授权数据)。所以我有 Slice for auth 这里是代码:

auth.js

import { createSlice } from '@reduxjs/toolkit'

export const authSlice = createSlice({
    name: 'auth',
    initialState: {
        isLoggedIn: false,
        token: null,
        role: null
    },
    reducers: {
        logIn: (state) => {
            state.isLoggedIn = true
        },
        role:(state, action) =>{
            state.role = action.payload
        },
        token:(state, action) =>{
            state.token = action.payload
        },
        logOut: (state) => {
            state.isLoggedIn = false
        },
    },
})

export default authSlice.reducer;



export const { logIn, logOut, role, token } = authSlice.actions

authService.js

import axios from 'axios';
import { api } from '../api/index'


export function authenticateUser(username, password) {

    axios
        .post(api + 'login', {username, password})
        .then(res => {
            console.log(res.headers.authorization)
        })
}

LoginForm.js

import React, { Component } from 'react';
import { Form, Col, Button } from 'react-bootstrap';
import { IoMdLogIn } from "react-icons/all";
import { authenticateUser } from '../services/authService'

export default class LoginForm extends Component{

    constructor(props) {
        super(props);
        this.state = this.initialState;
        this.credentialsChange = this.credentialsChange.bind(this);
        this.userLogin= this.userLogin.bind(this);

    }


    initialState = {
        username: '', password: ''
    }

    userLogin = (e) => {
        e.preventDefault();
        authenticateUser(this.state.username, this.state.password);
        this.setState( () => this.initialState)
    }

    credentialsChange = e => {
        this.setState({
            [e.target.name]:e.target.value
        });
    }

    render(){


        const {username, password} = this.state;

        return(
          <Form onSubmit={this.userLogin}   id="loginFormId">
              <Form.Row>
                  <Form.Group as={Col} controlId="formGridCountry">
                      <Form.Label>Username</Form.Label>
                      <Form.Control required autoComplete="off"
                                    type="text" name="username"
                                    value={username}
                                    onChange={this.credentialsChange}
                                    className={"bg-light"}
                                    placeholder="Username" />
                  </Form.Group>
              </Form.Row>
              <Form.Row>
                  <Form.Group as={Col} controlId="formGridZipCode">
                      <Form.Label>Password</Form.Label>
                      <Form.Control required autoComplete="off"
                                    type="password" name="password"
                                    value={password}
                                    onChange={this.credentialsChange}
                                    className={"bg-light"}
                                    placeholder="Password" />
                  </Form.Group>
              </Form.Row>
              <Button type="submit" variant="success">
                    <IoMdLogIn />
              </Button>
          </Form>
        );
    }

}

我想要达到的是:我想在调用函数 authenticateUser 后更新状态 isLoggedIn:true。

我尝试使用const dispatch = useDispatch(),然后调用dispatch(logIn()),但它会抛出错误。

我应该在哪里调用调度程序来更新状态?

【问题讨论】:

    标签: javascript reactjs redux-toolkit


    【解决方案1】:

    您需要在 api 响应中调用 AuthService.js 中的调度程序。 检查响应,如果没问题,存储它。如果你的 redux 实现得很好,它就会工作。

     axios
            .post(api + 'login', {username, password})
            .then(res => {
                console.log(res.headers.authorization)
                //Call it here, or create a function and call it here.
    
            })
    }
    

    如果它不起作用,请与我们分享错误

    【讨论】:

    • 像你说的那样调用调度程序:const dispatch = useDispatch(); 然后在 axios.post dispatch(token(jwtToken)) dispatch(logIn()) 这就是我得到的:react-dom.development.js:14906 未捕获的错误:无效的钩子调用。钩子只能在函数组件的主体内部调用。这可能是由于以下原因之一: 1. 你可能有不匹配的 React 版本和渲染器(例如 React DOM) 2. 你可能违反了 Hooks 规则 3. 你可能有多个 React 副本同一个应用
    • 你能把你的代码放在一个 git 仓库吗?然后我们可以确切地看到发生了什么
    猜你喜欢
    • 1970-01-01
    • 2022-12-21
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多