【问题标题】:Redux state is not working properly in functional componentsRedux 状态在功能组件中无法正常工作
【发布时间】:2020-02-28 00:24:01
【问题描述】:

我在使用 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?

【问题讨论】:

  • 功能组件无权访问dispatch。关注这些stackoverflow.com/a/47121068/5124488stackoverflow.com/a/39765573/5124488 ?
  • 这里有很多问题:LoginForm 不渲染任何东西,在闭包中捕获至少一个变量 (dispatch),这是一个很大的功能组件,不可以(它们是应该是 functional,即 props 的纯函数,并且只使用 hooks 来表示状态),大量的 HOF 间接等等。
  • 谢谢@blueseal。很抱歉,当我发布这个问题时,我忽略了“调度”。所以,我像这样再次编辑它。 ``` 常量调度 = useDispatch(); ```
  • 谢谢@JaredSmith,对不起,我没有“渲染”部分,因为它太基础了。我添加它们是为了更方便理解。我的问题又来了,你对“功能组件中的状态”真的没有任何问题吗?

标签: reactjs redux functional-programming components state


【解决方案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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 2013-10-29
    相关资源
    最近更新 更多