首页 > 解决方案 > 如何重写这个双箭头函数

问题描述

我有一个函数可以更新我的日程状态,一组艺术家对象。目前我正在使用一个双箭头函数,它接受索引和艺术家 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>
            );
        });

标签: javascriptreactjsecmascript-6

解决方案


如有必要,您可以修改 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);
}

推荐阅读