我有以下容器组件
import { connect } from "react-redux";
import LoginComponent from "./Login";
import React from "react";
export class LoginContainerComponent extends React.Component {
constructor( props ) {
super( props )
}
login( username, password ) {
//Perform actual login here
this.props.onLoginClick();
}
render() {
return (<LoginComponent onLoginClick = {this.login} />);
};
}
const mapStateToProps = function ( state ) {
return {
currentState: 'Logged Out'
}
};
const mapDispatchToProps = function ( dispatch ) {
return {
onLoginClick: () => {
alert( 'login clicked' );
}
}
};
export default connect( mapStateToProps, mapDispatchToProps )( LoginContainerComponent );
正如您在render()方法中看到的,我将容器组件的login方法传递给LoginComponent,它是一个表示组件。这个想法是
答案 0 :(得分:0)
在你的构造中,你必须将它绑定到你的登录方法。
import { connect } from "react-redux";
import LoginComponent from "./Login";
import React from "react";
export class LoginContainerComponent extends React.Component {
constructor( props ) {
super( props )
this.login = this.login.bind(this);
}
login( username, password ) {
//Perform actual login here
this.props.onLoginClick();
}
render() {
return (<LoginComponent onLoginClick = {this.login} />);
};
}
const mapStateToProps = function ( state ) {
return {
currentState: 'Logged Out'
}
};
const mapDispatchToProps = function ( dispatch ) {
return {
onLoginClick: () => {
alert( 'login clicked' );
}
}
};
export default connect( mapStateToProps, mapDispatchToProps )( LoginContainerComponent );
这是必需的,因为如果只将该函数传递给组件,则该组件不再可用。但是,如果你强迫&#34; - 绑定到方法它可用。
答案 1 :(得分:0)
react-redux可以为您提供此类事物,而无需使用connect
函数中很少使用的第三个参数创建自己的容器类:mergeProps
。
import { connect } from "react-redux";
import LoginComponent from "./Login";
import React from "react";
const mapStateToProps = function ( state ) {
return {
currentState: 'Logged Out'
}
};
const mapDispatchToProps = function ( dispatch ) {
return {
onLoginClicked: () => {
alert( 'login clicked' );
}
}
};
const mergeProps = function ( stateProps, dispatchProps ) {
return {
...stateProps,
onLoginClicked: (username, password) -> {
//Perform actual login here
dispatchProps.onLoginClicked()
}
}
};
export default connect( mapStateToProps, mapDispatchToProps, mergeProps )( LoginComponent );
这也绕过了bind
容器的login
功能的需要。