如何修复。TypeError:无法读取 null 的属性“用户”
2018-12-25
1512
尝试创建状态的副本,更新副本并将其分配回状态,但它会引发错误。
这是我的代码:
class App extends Component {
constructor(){
super()
this.State = {
user: {
username: '',
password: ''
}
}
}
updateuser = (attr, event) => {
console.log(attr + '==' + event.target.value);
let updateduser = Object.assign({}, this.state.user) // errored line
updateduser[attr] = event.target.value
this.setState({
user: updateduser
})
}
控制台错误:
App.js:17 Uncaught TypeError: Cannot read property 'user' of null
at App._this.updateuser (App.js:17)
at HTMLUnknownElement.callCallback (react-dom.development.js:147)
at Object.invokeGuardedCallbackDev (react-dom.development.js:196)
at invokeGuardedCallback (react-dom.development.js:250)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:265)
2个回答
这只是一个拼写错误,将 this.State 更改为 this.state ,
class App extends Component {
constructor(){
super()
this.state = { //fix
user: {
username: '',
password: ''
}
}
}
updateuser = (attr, event) => {
console.log(attr + '==' + event.target.value);
let updateduser = Object.assign({}, this.state.user) // errored line
updateduser[attr] = event.target.value
this.setState({
user: updateduser
})
}
Praveen Rao Chavan.G
2018-12-25
只需将
this.State
更新为
this.state
Tarreq
2018-12-25