Redux状态在功能组件中无法正常工作

时间:2019-11-01 17:55:36

标签: reactjs redux functional-programming components state

我在使用React功能组件时遇到问题。

import {signUp} from '../actions/user_actions';
import { useDispatch } from "react-redux";
// LoginForm.js

const LoginForm = props => {
  const dispatch = useDispatch();
  submitUser = () => {
    const formToSubmit = {email: 'some@abc.com', password: 'testpassword' };
    dispatch(signUp(formToSubmit)).then(() => {
      console.log("after login", props.User);
      // At first time of calling "submitUser", this is an empty object. {}
      // But, if I call it once more, it is not empty object.
    });
  }
  return (
     <View><Button title="Test Form" onPress={submitUser} /></View>
  )
};

const mapStateToProps = state => {User: state.User}
export default connect(mapStateToProps)(LoginForm);

// LoginScreen.js

const LoginScreen = props => {
  return <LoginForm User={props} />
}
const mapStateToProps = state => {User: state.User}
export default (mapStateToProps)(LoginScreen);


// user_actions.js

const signUp = formData => {
  const request = axios(...).then(...);
  return {
    type: 'SIGN_UP',
    payload: request
  }
};

// users_reducer.js
expot default (state={}, action) {
  switch(action.type) {
    case 'SIGN_UP':
      return {
        ...state,
        auth: {
          uid: '...'
        }
      }

  }
};

...

第一次调用“ submitUser”时,这是一个空对象。 {}
但是,如果我再次调用它,它不是一个空对象。

是否有解决此问题的方法,以便我可以及时获得props.User?

1 个答案:

答案 0 :(得分:1)

{mapStateToProps}方法已在类组件中使用。 由于您使用的是功能组件和{useDispatch}钩子,因此无需使用它和{connect}。

无论如何,使用钩子实时更改redux-store中的更改的最佳方法是{useSelector}


function LoginForm() {
  const dispatch = useDispatch();
  const user = useSelector(user => state.auth.id) //as you refered the user at the reducer

//this is just for console the updates
useEffect(() => {console.log(user)} , [user]);

  submitUser = () => {
    const formToSubmit = {email: 'some@abc.com', password: 'testpassword' };
    dispatch(signUp(formToSubmit))
  }
 return (
     <View><Button title="Test Form" onPress={submitUser} /></View>
  )
}

 export default LoginForm;