您好,我正在尝试从后端获取选项列表,然后将它们映射到选项列表并添加到列表中,但失败了。有人可以指教吗?

父组件:

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 消失了。

请您参考如下方法:

获得数组后,您无需手动创建元素。通过在渲染函数中映射数组本身,使用您的状态作为 JSX 元素的源。

试试这个:

fetch(urlMakerNames) 
.then((response) => response.json()) 
.then((responseJson) => { 
    var array = JSON.parse(responseJson.marker_names); 
 
    this.setState({ 
        markerNames: array 
    }); 
 
}).catch((error) => { 
    console.error("MarkerForm error = " + error); 
}); 
 
 
 
    <FormGroup> 
        <Input type="select" name="markerName" onChange={this.props.handleInputChange} disabled={this.props.isViewMode} required> 
            {this.props.markerNames.map((option, inx)=>{ 
              return <option key={inx} value={option}>{option}</option>; 
            })} 
        </Input> 
    </FormGroup> 


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!