使用依赖下拉菜单我想根据城市选择显示州和州内的城市。第一个下拉列表正确显示州,在第二个下拉列表中显示为城市创建的表格的完整列。
我使用 React JS 作为前端,使用 Node JS 作为服务器,MySql 作为数据库。 这里我附上了 React JS 代码片段。
import React, {
Component
} from 'react'
import './App.css';
class Axios extends Component {
constructor(props) {
super(props)
this.state = {
district_Id: '',
state_Id: '',
CountryData: [],
StateData: [],
}
}
componentDidMount() {
fetch('http://localhost:5001/state')
.then(response => response.json()) //response-from api and covert to json
.then(CountryData => this.setState({
CountryData: CountryData
}))
}
ChangeteState = (e) => {
this.setState({
state_Id: e.target.value
});
fetch('http://localhost:5001/district?state_Id=' + e.target.value)
.then(response => response.json()) //response-from api and covert to json
.then(StateData => this.setState({
StateData: StateData
}))
}
render() {
return ( <
div > < div class = "row"
className = "hdr" >
<
div class = "col-sm-12 btn btn-info" >
<
/div> <
/div> <
div className = "form-group dropdn" >
<
select className = "form-control"
name = "country"
value = {
this.state.state_Id
}
onChange = {
this.ChangeteState
} >
<
option > Select State < /option> {
this.state.CountryData.map((e, key) => {
return <option key = {
key
}
value = {
e.state_Id
} > {
e.state_name
} < /option>;
})
} <
/select> <
select className = "form-control slct"
name = "state"
value = {
this.state.StateId
} >
<
option > Select District < /option> {
this.state.StateData.map((e, key) => {
return <option key = {
key
}
value = {
e.state_Id
} > {
e.district_name
} < /option>;
})
} <
/select>
<
/div> <
/div>
)
}
}
export default Axios
Node JS 代码段:
var sql="SELECT *FROM state_table.new_table";
con.query(sql,function(err,users)
{
if (err)throw error;
res.send(JSON.stringify(users));
console.log(users);
});
});
app.get('/district',function(req,res)
{
var sql="SELECT *FROM state_table.district_name";
con.query(sql,function(err,user)
{
if (err)throw error;
res.send(JSON.stringify(user));
console.log(user);
});
我可以用硬编码数据做到这一点,当涉及到 MySql 数据库时,我正面临这个问题。 让我更清楚地说明问题,我附上了我面临的问题的图片。 Dropdown Misbehaviour
我是 React 和 MySql 的新手,关于这个问题的任何帮助或建议都会对我有很大帮助。
感谢 Adavnce。