我有一个更新的时间表我的状态,艺术家对象的数组功能。目前我使用的是双箭头函数,它在索引和艺术家ID。但是我不能用一个双箭头功能,由于我的javascript棉短绒。我该如何改写呢?
handleArtistChange = index => evt => {
if (evt) {
const newSchedule = this.state.schedule.map((artist, stateIndex) => {
if (index !== stateIndex) return artist;
return { ...artist, artist_id: evt.value };
});
this.setState({ schedule: newSchedule });
}
}
我曾尝试以下:
handleArtistChange = function(index) {
return function(evt) {
if (evt) {
const newSchedule = this.state.schedule.map((artist, stateIndex) => {
if (index !== stateIndex) return artist;
return { ...artist, artist_id: evt.value };
});
this.setState({ schedule: newSchedule });
}
}
}
然而这导致的错误无法读取的未定义的属性“日程”
我的函数调用:
const lineup = this.state.schedule.map((artist, index) => {
return (
<div key={index} className="form__input-group--lineup">
<div>
<label className="form__label">{getTextNode('Artist *')}</label>
<Select
onChange={this.handleArtistChange(index)}
onInputChange={this.handleInputChange}
isClearable
options={options}
styles={customStyles}
backspaceRemovesValue={false}
placeholder={`Artist #${index + 1}`}
classNamePrefix="react-select"
/>
</div>
<div className="form__input-group--time">
<label className="form__label">{getTextNode('start time *')}</label>
<input name="startTime" type="time" required autoComplete="true" className="form__input" value={this.state.startTime} onChange={this.handleTimeChange(index)} />
</div>
<button type="button">-</button>
</div>
);
});
如有必要,您可以修改您的掉毛的规则。如果你想修改你的功能,在这里是一种方法来定义它,与常规的函数返回绑定到外部this
一个匿名函数:
function handleArtistChange(index) {
return (function(evt) {
if (evt) {
const newSchedule = this.state.schedule.map((artist, stateIndex) => {
if (index !== stateIndex) return artist;
return { ...artist, artist_id: evt.value };
});
this.setState({ schedule: newSchedule });
}
}).bind(this);
}