2017-08-29 151 views
0

只是想知道我在做什麼錯在這裏。當我從列表中選擇一個值時,組件輸入字段沒有被填入值。反應選擇組件值不更新。

class Search extends Component { 
constructor(props) { 
    super(props); 
    this.state = { 
     name: 'order_select_field', 
     placeholder: "Make a selection", 
    } 
} 

componentWillMount() { 
    fetch('http://apirequest.com') 
     .then(function(response) { 
      return response.json(); 
     }) 
     .then(function(json) { 
      this.setState({options: json}); 
     }.bind(this)) 
    } 

handleChange(event) { 
    this.setState({ }) 
} 

render() { 
    return (
     <div> 
      <Select 
       name={this.state.name} 
       options={this.state.options} 
       placeholder={this.state.placeholder} 
      /> 
     </div> 
    ) 
} 

}

+0

不要在'componentWillMount'上使用ajax請求!順便說一下這個方法基本上就是構造器。 https://facebook.github.io/react/docs/react-component.html#componentwillmount –

+0

你在選擇組件中使用了什麼庫? –

+0

@JulianSoro我正在使用react-select – Jasonca1

回答

1

你的主要問題是你handleChange方法不設置值

handleChange = (event) => { 
    this.setState({ 
    ...this.state, 
    value: event.target.value 
    }) 
} 

與香草<select>組件,onChange事件必須在event.target一個一個DOMElement參考,並反應提供DOM元素上的value prop,你可以使用它來更新你的狀態。您是第三方<Select>組件可能有不同的事件簽名或期望。另外,由於我不知道您使用的是什麼庫,因此我提供了可將您的值追蹤爲「yourSelectKey」的狀態鍵,但您可以用正確的鍵替換它。如果它是嵌套屬性(對象的一部分),則可能需要添加spread運算符,以便其他值也可以被複制。

而且您需要將onChange事件處理程序添加到您選擇的組件。我建議您按照react docs而不是使用該庫。

<select 
    value={this.state.value} 
    onChange={this.handleChange}> 
    name={this.state.name}> 

    <option value="value1">Value 1</option> 
    <option value="value2">Value 2</option> 
    <option value="value3">Value 3</option> 

</select> 

遇到其他問題:

  • 您需要綁定handleChange你的對象實例。您可以在構造函數中使用行this.handleChange = this.handleChange.bind(this)或聲明handleChange作爲實例變量來完成此操作,如上所述。
  • 作爲評論者說,你應該避免在componentWillMount中執行獲取調用,但應該使用componentDidMount。這是初學者常犯的錯誤。
+0

@ Jasonca1我修改了這個答案,爲'