【问题标题】:How to use the updated value in redux store immediately after the action is dispatched in react js functional components在 react js 功能组件中调度操作后如何立即在 redux store 中使用更新的值
【发布时间】:2020-04-16 09:44:13
【问题描述】:

在HandleSignIn 函数中调度getActionUser Action 后需要更新“props.error”的值。 代码使用旧值“props.error”执行,即使它在操作被调度并更新 redux 存储后使用。

请帮助我在操作发送后立即获取更新的值

import React, { useState } from "react";
import { NavLink, Link, withRouter } from "react-router-dom";
import { connect} from 'react-redux';
import {getActiveUser} from "../../redux-store/actions/login";

const handleSignIn = async (e) => {
    e.preventDefault();
    setdisable(true);
    setTimeout(()=>{
      setdisable(false)
    },500);

    if(validateForm()){

      const user = { 'email': email, 'password': password };
      await props.getActiveUser(user);

      // need to use the updated value of (error) after getActiveUser is dispatched
      if(props.error){
       alert(props.error);
      }
      else{
      alert(props.error)
      }
   }

  }

  return (
    <div className={classes.container}>
      <GridContainer justify="center">

        <GridItem xs={12} sm={6} md={4}>
        <Snackbar
                      place="tr"
                      color="warning"
                      icon={AddAlert}
                      message="Invalid Credentials"
                      open={tl}
                      // closeNotification={() => setTL(false)}
                      // close
                    />
          <form>
            <Card login className={classes[cardAnimaton]}>

                <CardHeader
                className={`${classes.cardHeader} ${classes.textCenter}`}
                /*color=""*/
                style={{margin: '0'}}
              >
{/*                <h4 className={classes.cardTitle}>Log in</h4>
                <div className={classes.socialLine}>
                  {[
                    "fab fa-facebook-square",
                    "fab fa-twitter",
                    "fab fa-google-plus"
                  ].map((prop, key) => {
                    return (
                      <Button
                        color="transparent"
                        justIcon
                        key={key}
                        className={classes.customButtonClass}
                      >
                        <i className={prop} />
                      </Button>
                    );
                  })}
                </div>*/}
                <img src={Logo} alt="Paxafe" style={{height: '26px', marginTop: '1.5rem'}}/>
              </CardHeader>


              <CardBody>
                <CustomInput
                  labelText="Email..."
                  id="email"
                  formControlProps={{
                    fullWidth: true
                  }}
                  inputProps={{
                    endAdornment: (
                      <InputAdornment position="end">
                        <Email className={classes.inputAdornmentIcon} />
                      </InputAdornment>
                    ),
                    onChange: (e) => {
                      setEmail(e.target.value);
                    }
                  }}
                  onChange={e => setEmail(e.target.value)}
                />
                {emailError?(<p style={{color:'#e53935',marginTop:'-15px',position:'absolute'}}>{emailError}</p>):('')}
                <CustomInput
                  labelText="Password"
                  id="password"
                  formControlProps={{
                    fullWidth: true
                  }}
                  inputProps={{
                    endAdornment: (
                      <InputAdornment position="end">
                        <Icon className={classes.inputAdornmentIcon}>
                          lock_outline
                        </Icon>
                      </InputAdornment>
                    ),
                    type: "password",
                    autoComplete: "off",
                    onChange: (e) => {
                      setPassword(e.target.value);
                    }
                  }}

                />
                  {passwordError?(<p style={{color:'#e53935',marginTop:'-15px',position:'absolute'}}>{passwordError}</p>):('')}
              </CardBody>
              <CardFooter className={classes.justifyContentCenter}>
                <Button color="info" size="lg" block onClick={handleSignIn} type='submit' disabled={disable}>
                  Login
                </Button>

              </CardFooter>
            </Card>
          </form>
        </GridItem>
      </GridContainer>
    </div>
  );
}

const mapStateToProps = state =>{
  return {
    error:state.login.error
  }
}

export default withRouter(connect(mapStateToProps,{getActiveUser})(Login));

【问题讨论】:

    标签: reactjs redux react-hooks


    【解决方案1】:

    props 是对象并作为参数传递给handleSignIn 组件。它将使用error 更新,但仅在下一次渲染时更新。

    但您可以从getActiveUser 动作创建者返回error,如下所示

    const getActiveUser = user => dispatch => {
        /* do work */
        dispatch ({type: 'ERROR', error });
        return error;
    }
    

    并且你可以立即在组件中使用返回值

    const error = await props.getActiveUser (user)
    

    【讨论】:

    • 它的工作。但为什么我不能得到更新的 redux 值。以及如果没有获得价值,为什么要使用 redux
    • React 组件的想法是它 1. 获取道具 2. 在屏幕上渲染一些东西 3. 如果道具更新,它会重新渲染等等 所以当你在组件代码中时,porps 是静态的。道具将被更新和组件重新渲染。 React 将合并来自组件的更新并向用户呈现流畅的界面。当 props 是静态的时,开发组件比偶尔更改 props 更容易
    猜你喜欢
    • 1970-01-01
    • 2018-12-30
    • 2020-09-29
    • 2020-04-25
    • 2020-09-11
    • 1970-01-01
    • 2017-05-06
    • 2020-08-10
    • 2017-11-09
    相关资源
    最近更新 更多