我有3个状态值:username
,password
和address
,以及对应的3个文本框,其中我将各个状态的值包括在内。现在,我希望单击提交按钮,将这些状态添加到名为add_data
的状态数组上:
状态:
this.state = {
uname: '',
pass: '',
address:'',
salary:'',
add_data:[]
}
输入:
<div>
<label>username:</label>
<input type="text" noValidate name="uname" onChange={this.changeHandler} />
</div>
<div>
<label>password:</label>
<input type="password" noValidate name="pass" onChange={this.changeHandler} />
</div>
<div>
<label>address:</label>
<textarea noValidate name="address" onChange={this.changeHandler}></textarea>
</div>
<div>
<button onClick={this.submitForm}>Edit</button>
</div>
单击并更改功能:
changeHandler = e => {
var adddata_obj;
this.setState({ [e.target.name]: e.target.value })
}
submitForm = () => {
console.log(this.state);
this.setState({
add_data: [...this.state.add_data, { username: this.state.uname, password: this.state.pass, address: this.state.address }]
})
}
问题是,当我单击“编辑”按钮时,add_data
数组不会更新。相反,当我在文本框上进行其他更改时,它将显示最后一次单击时的值odt_data。请帮忙。
答案 0 :(得分:0)
这是一个完整的工作代码示例(在此处进行测试:https://codesandbox.io/embed/mq66o03r3j):
import React from "react";
import {render} from "react-dom";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
uname: "",
pass: "",
address: "",
salary: "",
add_data: []
};
}
changeHandler = e => {
this.setState({[e.target.name]: e.target.value});
};
submitForm = () => {
this.setState({
add_data: [
...this.state.add_data,
{
username: this.state.uname,
password: this.state.pass,
address: this.state.address
}
],
uname: "",
pass: "",
address: "",
salary: ""
});
};
render() {
return (
<div>
<div>
<label>username:</label>
<input
type="text"
name="uname"
onChange={this.changeHandler}
value={this.state.uname}
/>
</div>
<div>
<label>password:</label>
<input
type="password"
name="pass"
onChange={this.changeHandler}
value={this.state.pass}
/>
</div>
<div>
<label>address:</label>
<textarea
name="address"
onChange={this.changeHandler}
value={this.state.address}
/>
</div>
<div>
<button onClick={this.submitForm}>Edit</button>
</div>
<div>
<p>Saved data:</p>
<table>
<tr>
<td>User</td>
<td>Password</td>
<td>Address</td>
</tr>
{this.state.add_data.map(d => (
<tr>
<td>{d.username}</td>
<td>{d.password}</td>
<td>{d.address}</td>
</tr>
))}
</table>
</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
render(<App />, rootElement);
现在您可以自己发现错误了。当有不清楚的地方时,不要犹豫问我。
答案 1 :(得分:0)
您的代码在@ user3450590上工作正常,只需将add_data
呈现为列表https://stackblitz.com/edit/state-array-updating-on-next-click即可在此处查看您的代码段。
我唯一更改的是您记录状态的位置。 setSet
是异步的(请参见here),如果您需要注销更改,可以将其作为第二个参数传递给回调函数。
按照@virtusmaior的示例,您还将原始值保持在提交表单时可能要更改的状态。
此外,您的提交功能还可以从destructuring中受益,这是一个很好的小樱桃。即
submitForm = () => {
console.log(this.state);
this.setState(state => {
const { add_data, ...values } = state;
return {
add_data: [...add_data, { ...values }]
};
});
}