javascript - 如何重写这个双箭头函数
问题描述
我有一个函数可以更新我的日程状态,一组艺术家对象。目前我正在使用一个双箭头函数,它接受索引和艺术家 ID。但是,由于我的 javascript linter,我不能使用双箭头函数。我该如何重写这个?
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>
);
});
解决方案
如有必要,您可以修改 linting 规则。如果你想修改你的函数,这是一种定义它的方法,一个常规函数返回一个绑定到外部的匿名函数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);
}
推荐阅读
- jquery - Laravel vuejs 更改的选定索引
- javascript - 如何将 moment.updateLocale() 迁移到 date-fns 语言环境方法?
- annotations - Jape规则在一组句子中注释问题
- python - Opencv 从我的 python 代码中给出 C++ 异常错误
- android - 无法在 android studio 中设置 firebase
- javascript - 当我从父组件更改其状态时,为什么我的子组件没有更新?
- apache - 具有相同参数的多个页面的htaccess重写规则
- ffmpeg - .avi 文件到带有 alpha 通道的 .webm 文件
- python - 在 Windows 中安装 apex
- python-3.x - 如何将一维数据列表标准化为特定范围?