【发布时间】:2018-10-24 21:07:08
【问题描述】:
我正在开发一个 React Web 应用程序,需要保存表单提交中的输入,以便在多个 API 调用中重复使用。
我最初可以使用输入来进行 API 调用并显示结果,但我无法从表单中保存该输入以进行另一次调用。最终目的是让用户在输入搜索词后能够点击一个按钮以根据其他条件过滤响应。
我已经在下面注明了我想在代码中执行但不起作用的操作:
class Search extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
inputValue: '',
};
}
onInitialSearch = (e) => {
e.preventDefault();
////this value is what I use in the initial API call which is working
const { value } = this.input;
////this is what I'd like to be able to do but isn't working
//this logs nothing in console
this.setState({ inputValue : this.input}), function () {
console.log("inputValue is ",this.state.inputValue);
};
if (value === '') {
return;
}
this.fetchStories(value);
}
fetchStories = (value) => {
axios.get(getNews(value))
.then(response => {
this.setState({data: response.data.articles});
})
}
render() {
return (
<div className="page">
<div className="App-search">
<form type="submit" onSubmit={this.onInitialSearch}>
<input type="text" ref={node => this.input = node} />
<button type="submit">Search</button>
</form>
</div>
<div>
<List list={this.state.data} />
</div>
</div>
);
}
}
export default Search
【问题讨论】:
-
你为什么不把搜索状态放到另一个组件中,比如说
SearchContainer,然后你可以将你的过滤器和搜索表单添加为子元素并传递状态?这样,即使您完全删除了搜索字段子项,您的状态仍然存在。
标签: node.js forms reactjs variable-assignment