[英]React TypeError: this.props.handleSubmit is not a function
我已经构建了一个包装的 class 组件,该组件旨在使用带有 axios 的 API 请求提交数据。 但是,当我按下提交按钮时,我收到错误TypeError: this.props.handleSubmit is not a function
。
我已经构建了类似的组件并且它们有效,但由于某种原因我得到了这个 TypeError。 我错过了什么吗?
class AddPlayer extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
};
this.handleName = this.handleName.bind(this);
};
// Name Input
handleName = e => {
this.setState({
name: e.currentTarget.value
});
};
// handle form submit
handleSubmit = e => {
e.preventDefault();
this.props.handleClick({ ...this.state });
this.setState({
name: "",
});
};
render() {
const { name } = this.state;
return (
<form
onSubmit={this.handleSubmit}>
<h2>Input Player</h2>
<div>
<div >
<label htmlFor="player name">
Enter new Player Name:
</label>
<input
type="text"
id="player name"
name="player name"
value={name}
onChange={this.handleName}
maxLength="25"
minLength="2"
required
ref={function (input) {
if (input != null) {
input.focus();
}
}}
/>
</div>
<button disabled={name.length <= 2} type="submit">Add Player</button>
</div>
</form>
)
};
};
import { connect } from 'react-redux';
import AddPlayer from './AddPlayer';
import { postPlayer } from '../../data/actions/api';
// Dispatch
const mapDispatchToProps = dispatch => {
return {
handleClick: (data) => dispatch(postPlayer(data)),
};
};
export default connect(null, mapDispatchToProps)(AddPlayer)
react-redux connect
function 将mapStateToProps
作为第一个参数, mapDispatchToProps
作为第二个参数。 如果您没有mapStateToProps
,您可以只提供null
作为第一个参数。
export default connect(null, mapDispatchToProps)(AddPlayer)
编辑:对于记录保存,另一个问题是在其他地方使用它时导入未连接的组件而不是连接的组件。
请代替 onSubmit={this.handleSubmit} 做 onSubmit={()=>this.handleSubmit()} 和 onChange={this.handleName} 做 onChange={()=>this.handleName()}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.