我正在使用React。在componentDidMount中,我正在使用服务器=>接收数据(竞争对手)=>将数据保存在State中进行获取。我的选择代表此数据。当选择更改时,所选竞争对手的ID将保存在State中,以便在提交后将其发送到数据库。而且一切正常。但是,当页面加载后,我没有在select中更改任何内容,只是提交,此ID未发送,我知道为什么(onChange不执行),但是我不知道如何解决它,我无法设置默认状态手动,因为数据库中的数据可能不同。
这是我的状态:
state = {
promotions: [],
competitors: [],
draftCompetitorIdToPromote: "",
draftLevel: "",
draftDate: ""
};
这是我的componentDidMount:
componentDidMount = () => {
fetch("http://localhost:5000/competitors")
.then(response => response.json())
.then(data => this.setState({ competitors: data }));
fetch("http://localhost:5000/")
.then(response => response.json())
.then(data => this.setState({ promotions: data }));
};
这是我的onChange函数:
compChange = event => {
this.setState({
draftCompetitorIdToPromote: event.target.value
});
};
这是我的选择:
<select
value={this.state.draftCompetitorIdToPromote}
onChange={this.compChange}
className="form-control"
>
{this.state.competitors.map((competitor, index) => {
return (
<option value={competitor._id} key={index}>
{competitor.name}
</option>
);
})}
</select>
答案 0 :(得分:2)
为此,您需要在状态componentDidMount
中设置默认值,并在数据加载后将competitors[0]._id
设置为draftCompetitorIdToPromote
的默认值
componentDidMount = () => {
fetch("http://localhost:5000/competitors")
.then(response => response.json())
.then((data => this.setState({
competitors: data,
draftCompetitorIdToPromote: data[0]._id,
}));
fetch("http://localhost:5000/")
.then(response => response.json())
.then(data => this.setState({ promotions: data }));
};