2016-07-26 131 views
2

我試圖更新我的城市從選定的狀態來選擇反應,但是當我改變國家的城市不更新:更新選擇從另一個選擇選項

這裏是我的渲染代碼的一部分:

<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 

任何想法來解決我的問題?

回答

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) 
     } 
    }); 
} 
+0

我不使用componentDidMount(),對吧? –

+1

你需要兩個。 componentDidMount在第一次裝載時觸發一次,componentWillReceiveProps在每次道具更新時觸發。這就是爲什麼我已經提取'loadItems'來分離方法。順便說一下,在那裏通知爭論 –

+0

好吧,我在這裏嘗試,我注意到你,如果我得到它:) –

相關問題