嗨,我正在尝试从后端获取选项列表,然后将它们映射到选项列表并添加到列表中,但失败了。有人可以请教吗?
父组件:
fetch(urlMakerNames)
.then((response) => response.json())
.then((responseJson) => {
var array = JSON.parse(responseJson.marker_names);
var options = array.map((opt, index) => {
console.log('opt = ' + opt + ', index = ' + index);
return '<option key="' + index + '" value="' + opt + '">' + opt + '</option>';
});
console.log('BEFORE options = ' + options + ', markerNames = ' + this.state.markerNames);
this.setState({
markerNames: options
});
console.log('AFTER options = ' + options + ', markerNames = ' + this.state.markerNames);
}).catch((error) => {
console.error("MarkerForm error = " + error);
});
子组件:
console.log('this.props.markerNames = ' + this.props.markerNames);
<FormGroup>
<Input type="select" name="markerName" onChange={this.props.handleInputChange} disabled={this.props.isViewMode} required>
<option key="12345" value="TEST">TEST</option>
{this.props.markerNames}
</Input>
</FormGroup>
日志显示:
opt = zzz, index = 0
BEFORE options = <option key="0" value="zzz">zzz</option>, markerNames =
this.props.markerNames = <option key="0" value="zzz">zzz</option>
AFTER options = <option key="0" value="zzz">zzz</option>, markerNames = <option key="0" value="zzz">zzz</option>
从日志中可以看出,markerNames 以正确的格式传递到子组件中,匹配<option key="12345" value="TEST">TEST</option>
但在输入选择元素中只能看到 TEST 选项,但 zzz 消失了。