使用webpacker運行React和Rails 5.2。將反應組件的屬性傳遞給rails後端
我在頁面頂部有一個ElasticSearch搜索欄,我無法將正確的請求發送到後端,並且允許rails後端處理搜索請求。
我們現在沒有準備好將此作爲SPA的權利,但我似乎無法得到填充的參數。
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {asyncContainer, Typeahead} from 'react-bootstrap-typeahead';
const AsyncTypeahead = asyncContainer(Typeahead);
class SearchBar extends Component {
constructor(props) {
super(props)
this.state = {
options: ['Please Type Your Query'],
searchPath: '/error_code/search',
selected: [""],
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
searchErrorCodes(term) {
fetch(`/error_code/auto?query=${term}`)
.then(resp => resp.json())
.then(json => this.setState({options: json}))
}
handleChange(error_code_name) {
let newValue = error_code_name
this.setState({
selected: newValue
});
this.setState({
searchPath: `/error_code/search?error_code=${this.state.selected}`,
});
console.log(`This is the new searchPath is ${this.state.searchPath}`);
}
handleSubmit(e) {
alert(`submitted: ${this.state.selected}`);
// event.preventDefault();
}
render() {
return (
<div>
<form ref="form"
action={this.state.searchPath}
acceptCharset="UTF-8"
method="get"
onSubmit={e => this.handleSubmit(e)}
>
<AsyncTypeahead
onSearch={term => this.searchErrorCodes(term)}
options={this.state.options}
className="search"
onClick={e => this.handleSubmit(e)}
selected={this.state.selected}
onChange={e => this.handleChange(e)}
/>
<button
action={this.state.searchPath}
acceptCharset="UTF-8"
method="get"
type="submit"
className="btn btn-sm btn-search">
<i className="fa fa-search"></i>
</button>
</form>
</div>
)
}
}
ReactDOM.render(<SearchBar/>, document.querySelector('.search-bar'));
一切都呈現正確,但輸入未正確發送到控制器。
當您觸發'this.setState({searchPath:'/ error_code/search?error_code = $ {this.state.selected}', });'時,它會發送'this的舊值。 state.selected',而不是你剛剛設置的那個? – Denialos
據我可以告訴它得到更新,但當你點擊提交時,表單按鈕或某些東西不會傳遞該更新。並且它沒有發送數據到後端 –
我會在你回答這個問題後添加到我的答案中。你如何從'onChange = {e => this.handleChange(e)}'獲得'error_code_name'?在這種情況下,內聯es6箭頭功能是無關緊要的,並且還會導致性能問題並打破淺層比較。 –