我正在尝试从所选状态更新我的城市选择,但是当我更改状态时城市不会更新:
以下是渲染代码的一部分:
<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
有什么想法解决我的问题吗?
答案 0 :(得分:2)
由于您要动态设置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)
}
});
}