我有一个具有单一状态的非常简单的组件,我在创建组件时初始化状态,并尝试在提交表单时更改它。
由于某种原因,它不起作用。
import React, { Component } from "react";
export default class AddTodo extends Component {
constructor() {
super();
this.state = {
submited: false
};
}
handleSubmit = event => {
this.setState = {
submited: true
};
alert("Submited state: " + this.state.submited);
event.preventDefault();
};
render() {
return (
<div className="container mt-3">
<form onSubmit={this.handleSubmit}>
<div className="input-group mb-3">
<input
type="text"
className="form-control"
placeholder="New Todo Description Here"
/>
<div className="input-group-append">
<button className="btn btn-primary" type="submit">
Add Todo
</button>
</div>
</div>
</form>
</div>
);
}
}
答案 0 :(得分:3)
this.setState
是一个函数,因此使用方括号()对其进行调用。
this.setState({
submited: true
});
答案 1 :(得分:0)
import React, { Component } from "react";
export default class AddTodo extends Component {
constructor() {
super();
this.state = {
submited: false
};
}
handleSubmit = event => {
this.setState({
submited: true
},()=>{
alert("Submited state: " + this.state.submited);
event.preventDefault();
});
};
render() {
return (
<div className="container mt-3">
<form onSubmit={this.handleSubmit}>
<div className="input-group mb-3">
<input
type="text"
className="form-control"
placeholder="New Todo Description Here"
/>
<div className="input-group-append">
<button className="btn btn-primary" type="submit">
Add Todo
</button>
</div>
</div>
</form>
</div>
);
}
}
答案 2 :(得分:0)
您可以看到here setState
是一个函数,但是您正在为其赋值。
问题在这里:
this.setState = {
submited: true
};
应该是:
this.setState({submitted: true}); // Mind the typo also
为了快速说明一下,React团队在版本16.8中发布了react钩子,以替换具有某些缺点的类组件。我会尝试一下,文档是here。
带有钩子的代码如下:
import React, { useState } from 'react';
function AddTodo() {
// Declare a new state variable, which we'll call "count"
const [isSubmitted, setSubmission] = useState(false);
function handleSubmit(event) {
setSubmission(true);
event.preventDefault();
}
return (
<div className="container mt-3">
<form onSubmit={handleSubmit}>
<div className="input-group mb-3">
<input
type="text"
className="form-control"
placeholder="New Todo Description Here"
/>
<div className="input-group-append">
<button className="btn btn-primary" type="submit">
Add Todo
</button>
</div>
</div>
</form>
);
}