我正在尝试创建状态副本,更新该副本并将其分配回该状态,但会引发错误。
这是我的代码:
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)
答案 0 :(得分:1)
这只是一个错字,请将 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
})
}
答案 1 :(得分:0)
只需将this.State
更新为this.state