问题描述
我在单独的 react 文件 <select>
中创建了一个自定义的 dropdown.js
组件,它应该有 <option>
个子组件,每个子组件都有基于从服务器获取的数据的值和标签。每个 <option>
都应包含美国各州的名称作为标签,以及它们各自的代码作为 value
和 key
属性的值。
例如
<select id="voter_state" aria-label="Choose State">
<option defaultValue>Choose State</option>
<option key="6" value=6>California</option>
<option key="36" value=36>New York</option>
...
</select>
App.js
文件应该在使用以下自定义 props
从服务器(通过 axios)成功获取所需数据后呈现选择组件:id
、label
、 options
。前两个道具已成功呈现,而 options
的数据未显示。
The needed elements are not showing
服务器端请求成功响应所需的数据,并且可以通过 App.js
文件中的 console.log() 显示。在从数据服务模块 allStates
的 GET 请求方法 getAll()
分配新值后,我还记录了更新状态 StateDataService
。这是我的 App.js
代码
import { Component } from 'react'
import ReactDOM from 'react-dom'
import 'bootstrap/dist/css/bootstrap.min.css'
import StateDataService from './services/states.service'
import Dropdown from './components/dropdown'
function extractValues(o,i) {
let a = Object.values(o)
return a[i]
}
class App extends Component {
constructor(props) {
super(props)
this.state = {
allStates: [],}
}
componentDidMount() {
var options = []
StateDataService
.getAll()
.then(res => {
res.data.forEach((datum) => {
options.push({
value: extractValues(datum,0),label: extractValues(datum,1)
})
})
})
.then(() => {
this.setState(() => {
return {
allStates: options
}
})
})
.then(() => {
ReactDOM.render(
<Dropdown choices={this.state.allStates} id="voter_state" label="Choose State" />,document.getElementById("rut")
)
})
.catch(err => {
console.log(err)
})
}
render() {
return (
<div>
<div id="rut"></div>
</div>
)
}
}
export default App
这是dropdown.js
组件的代码
import 'bootstrap/dist/css/bootstrap.min.css'
function Dropdown(props) {
const choices = props.choices
const dropdownItems = choices.forEach((choice) =>
<option key={choice.value.toString()} value={choice.value}>{choice.value}</option>
)
return (
<select className={props.id} aria-label={props.label}>
<option defaultValue>{props.label}</option>
{dropdownItems}
</select>
)
}
export default Dropdown
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)