我试图将一个动作映射到道具,但是我遇到一个错误: TypeError:_this2.props.updateUsername不是函数
一个人如何成功地将redux动作映射到props并成功调用该函数?我没有看到此错误出现在任何其他stackoverflow问题/答案中,这是一个简单的错误吗?可能是.index或.app中的redux设置错误吗?
我尝试过: -导入时不使用默认导出 -具有不同格式的mapDispatchToProps(例如,不使用bindactioncreators) -修正错字
组件:
import { updateUsername } from "../../actions/user-actions";
import React, { Component } from "react";
import { InputText } from "primereact/inputtext";
import { Button } from "primereact/button";
import { Password } from "primereact/password";
import "./UserLogin.css";
import { connect } from "react-redux";
import { bindActionCreators } from 'redux'
export class UserLoginPage extends Component {
constructor(props) {
super(props);
this.state = { //used to be using states so ill leave these here for now
username: "",
password: "",
renderTryAgain: false
};
this.checkLoginDetails.bind(this.checkLoginDetails);
}
async checkLoginDetails() {
...
}
render() {
const usernameBox = (
<InputText
...
value={this.props.username}
onChange={e => this.props.updateUsername(e.target.value)}
/>
);
const passwordBox = (
<Password
...
/>
);
const loginButton = (
<Button
...
/>
);
return (
<header className="User-login">
<p>Dashboard User Login</p>
<div className="p-grid">
<div className="p-col">{usernameBox}</div>
<div className="p-col">{passwordBox}</div>
<div className="p-col">{loginButton}</div>
</div>
</header>
);
}
}
const mapStateToProps = state => ({
username: state.username
});
const mapDispatchToProps = dispatch => bindActionCreators(
{
updateUsername,
},
dispatch,
)
export default connect(
mapStateToProps,
mapDispatchToProps
)(UserLoginPage);
减速器:
import { UPDATE_USERNAME} from '../actions/user-actions'
export function passReducer(state = "", {type, payload}) {
switch (type) {
case true:
return payload
default:
return state
}
}
export function usernameReducer(state = '', {type, payload}) {
switch (type) {
case UPDATE_USERNAME:
return payload.username
default:
return state
}
}
export default { passReducer, usernameReducer };
操作:
export const UPDATE_USERNAME = 'username:updateUsername'
export function updateUsername(newUsername){
return {
type: UPDATE_USERNAME,
payload: {
username: newUsername
}
}
}
export default {UPDATE_USERNAME, updateUsername}
非常感谢
答案 0 :(得分:1)
按如下所示更新构造函数后可以检查一次吗?
constructor(props) {
super(props);
//...
}
答案 1 :(得分:1)
请勿使用mapDispatchToProps。相反,只需将要映射的所有动作包装在一个对象中,然后将它们作为第二个参数传递给connect helper方法。
赞这个connect(mapStateToProps, { updateUsername })(UserLoginPage)
希望这会有所帮助!