如何在React中更新检索到表单的数据?单击(索引)链接后,我进入带有表单的新视图。 React从状态中检索数据,但是我无法编辑表单中的数据。
List.js
import React, { Component } from "react";
import { Switch, Route, BrowserRouter as Router, Link } from "react-router-dom";
import SingleUser from "./SingleUser";
class List extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
login: "",
pass: ""
};
this.add = this.add.bind(this);
this.show = this.show.bind(this);
this.del = this.del.bind(this);
}
add(e) {
e.preventDefault();
this.setState({
[e.target.name]: e.target.value
});
}
show(e) {
e.preventDefault();
if (!this.state.login.length || !this.state.pass.length) {
return;
} else {
const newUser = {
login: this.state.login,
pass: this.state.pass
};
this.setState(state => ({
data: state.data.concat(newUser)
}));
}
}
del(index) {
let { data } = this.state;
data.splice(index, 1);
this.setState({
data
});
}
render() {
return (
<div>
<form onSubmit={this.show}>
<label>Login</label>
<br />
<input type="text" name="login" onChange={e => this.add(e)} />
<br />
<label>Password</label>
<br />
<input type="text" name="pass" onChange={e => this.add(e)} />
<br />
<input type="submit" value="Add" />
</form>{" "}
<table>
<Router>
<div>
<Switch>
<Route exact path="/">
{this.state.data.map((val, index) => (
<>
<td>{val.login}</td>
<td>{val.pass}</td>
<br />
<div>
<div>
<Link to={`/${index}`}>{index}</Link>
</div>
</div>
<input
type="submit"
value="X"
onClick={() => this.del(index)}
/>
</>
))}
</Route>
<Route exact path="/:userID">
<SingleUser sData={this.state.data} />
</Route>
</Switch>
</div>
</Router>
</table>
</div>
);
}
}
export default List;
SingleUser.js
import React, { useState } from "react";
import { useParams, Link } from "react-router-dom";
function SingleUser(props) {
let { userID } = useParams();
const [temp, setCount] = useState("");
return (
<p>
<>
<div>{userID}</div>
Password: <input type="text" value={props.sData[userID].pass} />
<br />
Login: <input type="text" value={props.sData[userID].login} />
<br />
</>
<button onClick={() => setCount((props.sData[userID].pass = "password"))}>
Change
</button>
<br />
<Link to="/">Return</Link>
</p>
);
}
export default SingleUser;
我必须在这里使用react hook吗?