您好,我只想弄清楚为什么我会收到此错误 - TypeError:无法读取属性' fishes'未定义的。我错过了什么?
我的App.js:
class App extends Component {
constructor() {
super();
this.state = {
fishes : {},
order : {}
}
}
addFish(fish) {
var timestamp = (new Date()).getTime();
// update the state object
this.state.fishes['fish-' + timestamp] = fish;
// set the state
this.setState({ fishes : this.state.fishes });
}
render() {
return (
<div className="ui container"><br/>
...
然后是我的AddFishForm:
class AddFishForm extends Component {
createFish(event) {
event.preventDefault();
var fish = {
name : this.refs.name.value,
price : this.refs.price.value,
status : this.refs.status.value,
desc : this.refs.desc.value,
image : this.refs.image.value
}
this.props.addFish(fish);
this.refs.fishForm.reset();
}
render() {
return (
<form className="ui equal width form" ref="fishForm" onSubmit=
{this.createFish.bind(this)}>
<div className="fields">
...
答案 0 :(得分:2)
您可能忘记绑定您的方法。 此外,我建议在需要时传播您的状态对象。
App.js
constructor() {
super();
this.state = {
fishes: {},
order: {}
}
// THIS IS MISSING
this.addFish = this.addFish.bind(this)
}
...
addFish(fish) {
const timestamp = (new Date()).getTime();
this.setState({
fishes: {
...this.state.fishes,
['fish-' + timestamp]: fish
}
})
}
答案 1 :(得分:1)
您的状态初始化很好,但addFish
方法的this
上下文错误,因为您没有绑定/自动绑定它。
将其更改为
constructor() {
super();
this.state = {
fishes: {},
order: {}
}
this.addFish = this.addFish.bind(this);
}