更新选择从另一个选择选项
问题描述:
我试图更新我的城市从选定的状态来选择反应,但是当我改变国家的城市不更新:更新选择从另一个选择选项
这里是我的渲染代码的一部分:
<div>
<label for="state">state:</label>
<SelectInput items="RO-DF-RS-SP-RJ-MG-PR" onChange={this.handleChange} name="state"/>
</div>
{!!this.state.stt &&
(
<div>
<label for="city">city:</label>
<SelectInput url="/static/json/" filename={this.state.stt} onChange={this.props.onChange} name="city"/>
</div>
)
}
<div>
this.props.onChange
只是一个处理程序来获取输入值的数据在数据库
和代码保存:
handleChange(event){
if(event.target.name == "state"){
this.setState({
stt: event.target.value
});
}
if(this.props.onChange) {
this.props.onChange(event);
}
}
套正确的状态(this.state.stt)
这里是我的SelectInput:
class SelectInput extends React.Component{
constructor(props){
super(props);
this.state = {
select: "",
items: [],
filename: this.props.filename
}
this.handleChange = this.handleChange.bind(this)
}
componentDidMount(){
if(this.props.filename){
console.log(this.props.filename);
}
if(this.props.items){
this.setState({
items: this.props.items.split("-")
})
}
else if(this.props.url && this.props.filename){
$.ajax({
type: 'GET',
url: `${this.props.url}${this.props.filename}.json`,
headers: { 'Authorization': "Token " + localStorage.token },
success: (result) => {
this.setState({
items: result.child
})
},
error: function (cb) { console.log(cb) }
});
}
}
handleChange(event){
this.setState({
select: event.target.value
});
if(this.props.onChange) {
this.props.onChange(event)
}
}
render(){
return (
<select name={this.props.name} value={this.state.select} onChange={this.handleChange}>
<option value=""></option>
{this.state.items && this.state.items.map(item =>
<option value={item}>{item}</option>
)}
</select>
)
}
}
export default SelectInput
任何想法来解决我的问题?
答
由于您正在动态设置filename
,您需要实施componentWillReceiveProps
,这将使ajax请求加载新文件。
componentWillReceiveProps({ filename }) {
if(filename !== this.props.filename) {
this.loadItems(filename)
}
}
loadItems(filename) {
$.ajax({
type: 'GET',
url: `${this.props.url}${filename}.json`,
headers: {
'Authorization': "Token " + localStorage.token
},
success: (result) => {
this.setState({
items: result.child
})
},
error: function(cb) {
console.log(cb)
}
});
}
我不使用componentDidMount(),对吧? –
你需要两个。 componentDidMount在第一次装载时触发一次,componentWillReceiveProps在每次道具更新时触发。这就是为什么我已经提取'loadItems'来分离方法。顺便说一下,在那里通知争论 –
好吧,我在这里尝试,我注意到你,如果我得到它:) –