I want to display a modular window by clicking the Login or Register button, and I get the following error (TypeError: _this.props.dispatch is not a function). The same code in one project usually works in another.
import React from "react";
import { Link } from "react-router-dom";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { openModal } from "../modal/index";
import Login from "../auth/Login";
import Register from "../auth/Register";
class Navbar extends React.Component {
static propTypes = {
dispatch: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.login = this.login.bind(this);
this.register = this.register.bind(this);
}
login() {
this.props.dispatch(
openModal({content: <Login />,title: "Login"}));
}
register() {
this.props.dispatch(
openModal({content: <Register />,title: "Register"}));
}
render() {
const guestLinks = (
<ul className="navbar-nav ml-auto">
<li className="nav-item">
<button
className="m-1 btn-sm btn btn-outline-primary mt-1"
onClick={this.register}>Register</button>
</li>
<li className="nav-item">
<button
className="m-1 btn-sm btn btn-outline-primary mt-1"
onClick={this.login}>Login</button>
</li>
</ul>
);
return (
<nav className="navbar navbar-expand-sm navbar-light bg-light mb-4">
<div className="container">
<Link className="navbar-brand" to="/">
Domras
</Link>
<button
className="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#mobile-nav">
<span className="navbar-toggler-icon" />
</button>
<div className="collapse navbar-collapse" id="mobile-nav">
<ul className="navbar-nav mr-auto">
<li className="nav-item">
<Link className="nav-link" to="/profiles">
Driver
</Link>
</li>
</ul>
</div>
</div>
</nav>
);
}
}
const mapStateToProps = state => ({
auth: state.auth,
});
export default connect(mapStateToProps)(Navbar);
Welcome to Stack Overflow.
If everything is correct, you shouldn't get a problem.
The error message suggests that the dispatch
property is something other than a function - if so you should be getting a warning in the console.
A tip to save you some code... use fat arrow functions as below, these are automatically bound to this
, so you don't need to bind them in your constructor:
constructor(props) {
super(props);
// No longer needed
// this.login = this.login.bind(this);
// this.register = this.register.bind(this);
}
login = () => {
this.props.dispatch(
openModal({content: <Login />,title: "Login"}));
}
register = () => {
this.props.dispatch(
openModal({content: <Register />,title: "Register"}));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.