在反应-Redux的表象的组分使用麻烦的操作(Trouble using actions in re

2019-09-29 07:24发布

我是新来的终极版,并有麻烦缠绕我的头周围的表象和容器组件。

有关堆栈:

  • 反应v0.14.8
  • 反应本土v0.24.1
  • 终极版V3.5.2
  • 反应-终极版v4.4.5

问题:

我有一个登录按钮组件,它呈现检查时的登录状态,并调用onSuccessfulLogin行动与用户的Facebook凭证更新状态。

然而,试图将此分成独立的表象/容器组件的时候,我无法拨打onSuccessfulLogin行为: Error: onSuccessfulLogin is not defined

我在做什么错在这里? 我想像有一些简单,我不是通过两个部件和之间的关系理解connect()函数。

表象成分(Login.js)

import React, { PropTypes } from "react-native";
import FBLogin from "react-native-facebook-login";
import UserActions from "../users/UserActions";

class LoginPage extends React.Component {

    render() {

        const { userData, onSuccessfulLogin } = this.props;

        return (
          <FBLogin
              permissions={["email","user_friends"]}
              onLoginFound= { data => {
                  onSuccessfulLogin(data.credentials);
              }}
              />
        )
    }
};

export default LoginPage;

容器组件(LoginContainer.js)

import { connect } from 'react-redux';
import LoginPage from "../login/LoginPage";
import UserActions from "../users/UserActions";

const mapDispatchToProps = (dispatch) => {
  return {
    onSuccessfulLogin: (userData) => {
      dispatch(UserActions.userLoggedIn(userData))
    }
  }
}

const mapStateToProps = (state) => {
  return {
    userData: state.userData
  }
}

const LoginContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(LoginPage);

export default LoginContainer;

另外,如果我想使更新state.userData访问的LoginPage组件,我将如何做呢? 任何帮助表示赞赏!

解决了! 当使用ES6类,你需要调用super(props)的构造方法,以访问连接的表象组件容器的属性:

class LoginPage extends React.Component {
    constructor(props){
        super(props);
    }

    render(){    
        // ...
    }
}

Answer 1:

您的容器组件被认为是一个组件 ,它必须与要渲染哑/表象组件的渲染功能

import { connect } from 'react-redux';
import LoginPage from "../login/LoginPage";
import UserActions from "../users/UserActions";


class LoginContainer extends React.Component {
    constructor(props){
      super(props);
    }
    render() {
        return (
          <LoginPage userData={this.props.userData}
              onSuccessfulLogin={this.props.onSuccessfulLogin}
              />
        )
    }
};

const mapDispatchToProps = (dispatch) => {
  return {
    onSuccessfulLogin: (userData) => {
      dispatch(UserActions.userLoggedIn(userData))
    }
  }
}

const mapStateToProps = (state) => {
  return {
    userData: state.userData
  }
}


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


文章来源: Trouble using actions in react-redux presentational component