在功能组件中使用mapStateToProps和mapDispatchToProps调用redux操作后如何获取更新的属性

2wnc66cl  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(149)

这是我的集装箱

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Login from './Login';
import { loginAction } from './LoginAction';

const mapStateToProps = (state, ownProps) => {
  console.log('mapStateToProps', state)
  return {
    payload: state.Auth
  };
};

const mapDispatchToProps = dispatch => {
  console.log('mapDispatchToProps')
  return bindActionCreators(
    {
      loginAction
    },
    dispatch
  );
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Login);

这是我组件中的函数

const handleSubmit = async (event) => {

    const form = event.currentTarget
    if (form.checkValidity() === false) {
      event.preventDefault()
      event.stopPropagation()
      return false
    }
    setValidated(true)

    props.loginAction(username, password).then(() =>{
      console.log('props loginAction', props) // this props not updated immediately after loginAction called
      if (props.payload.error){
        return false
      }
    })

    // navigate('/dashboard')
  }

  useEffect(()=>{console.log('payload effect', props.payload)},[props.payload])

这是我的减速器

import * as types from './LoginActionTypes';

var initialState = {
  loading: false,
  result: null,
  error: null,
  message: null,
};

function AuthReducer(state = initialState, action) {
  switch (action.type) {
    case types.ACTION_REQUEST:
      return Object.assign({}, state, {
        loading: true,
        error: null
      });
      break;
    case types.AUTHENTICATED:
      return Object.assign({}, state, {
        loading: false,
        status: true,
        result: action.payload
      });
      break;
    case types.AUTHENTICATION_ERROR:
      return Object.assign({}, state, {
        loading: false,
        status: false,
        error: action.error
      });
      break;
    case types.UNAUTHENTICATED:
      return Object.assign({}, state, initialState);
      break;
    default:
      return state;
  }
}

export default AuthReducer;

我的问题是如何在我调用loginAction后得到更新的道具?2当我使用react组件时工作正常,但我不确定问题是否出在功能组件上,有什么建议吗?

props.loginAction(username, password).then(() =>{
      console.log('props loginAction', props) // this props not updated immediately after loginAction called
      if (props.payload.error){
        return false
      }
    })

this console that proof props mapStateToProps have new props, but the props still not updated, and useEffect is updated

6qftjkof

6qftjkof1#

要获得实际道具:

//add this
const propsRef = React.useRef(props);
propsRef.current = props;

props.loginAction(username, password).then(() =>{
      console.log('props loginAction', propsRef.current) // <-- change this
      if (propsRef.current.payload.error){ // <--- and this
        return false
      }
    })

相关问题