我构建了一个封装的类组件,用于使用带有 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)
答案 0 :(得分:1)
react-redux connect
函数将 mapStateToProps
作为第一个参数,mapDispatchToProps
作为第二个参数。如果您没有 mapStateToProps
,您可以只提供 null
作为第一个参数。
export default connect(null, mapDispatchToProps)(AddPlayer)
编辑:为了记录保存,另一个问题是在其他地方使用时导入未连接的组件而不是已连接的组件。
答案 1 :(得分:0)
请代替 onSubmit={this.handleSubmit} 做 onSubmit={()=>this.handleSubmit()} 并且与 onChange={this.handleName} 一样做 onChange={()=>this.handleName( )}