我试图在react中创建一个更改密码页面,并且我收到typeError:无法读取null的属性'users'。该代码适用于其他表单页面(我正在执行PUT和CREATE的页面),但不适用于此页面
我尝试将提交处理程序绑定到this关键字,但这没有用。 还尝试将handlePasswordChange绑定到this关键字
./formchange
import React from "react";
import { Link } from "react-router-dom";
var createReactClass = require("create-react-class");
var FormChange = createReactClass({
//setting initial state
getInitialState() {
return {
password: {}
};
},
handlePasswordChange(e) {
this.setState({
password: e.target.value
});
},
handleSubmit(e) {
e.preventDefault();
this.props.onSubmit(this.state);
this.props.history.push("/");
},
render() {
return (
<form
name="categories_post"
className="form-horizontal"
onSubmit={this.handleSubmit}
>
<div id="change_password">
<div className="form-group">
<label
className="col-sm-2 control-label required"
htmlFor="password"
>
Password
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.password}
onChange={this.handlePasswordChange}
id="password"
className="form-control"
/>
</div>
</div>
<button
type="submit"
id="formChangeSubmit"
className="btn btn-default"
>
Submit
</button>
</div>
</form>
);
}
});
export default FormChange;
./passwordupdate
import React from "react";
import { updateUsers, fetchUsers } from "./actions/appactions";
import FormChange from "./formchange";
var createReactClass = require("create-react-class");
const Update = createReactClass({
getIntitialState() {
return {
users: {}
};
},
componentWillReceiveProps(props) {
this.setState(props);
},
componentDidMount() {
fetchUsers(this.props.match.params.usersId)
.then(data => {
this.setState(state => {
state.users = data;
return state;
});
})
.catch(err => {
console.error("error", err);
});
},
handleSubmit(data) {
updateUsers(this.state.users.id, data);
},
render() {
return (
<div>
<FormChange
onSubmit={this.handleSubmit.bind}
password={this.state.users.password}
/>
</div>
);
}
});
export default Update;
//fetchusers function
export function fetchUsers(id) {
return fetch("https://localhost:44341/api/users/" + id, {
method: "GET",
mode: "cors"
})
.then(res => res.json())
.catch(err => err);
}
答案 0 :(得分:0)
<FormChange
onSubmit={this.handleSubmit.bind(this)}
password={this.state.users.password}
/>
进行此更改并检查
答案 1 :(得分:0)
我不确定,但是handleSubmit中有数据作为参数,但是您没有传递它。
尝试
您可以这样调用函数:
handleSubmit=(data)=> {
updateUsers(this.state.users.id, data);
},
并调用它
onSubmit={(data)=> this.handleSubmit(data)}
答案 2 :(得分:0)
问题出在subView
中。状态始终为空,必须将其更改为此
ComponentDidMount()
我最初是这样做的,因为这就是我其他更新文件的工作方式。希望这对其他人有用。