我正在使用React网络应用,需要将表单提交中的输入保存到多个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
答案 0 :(得分:1)
控制输入字段。
**Day 1**
We have reached a certain level of authenticity
You had a chat with Falon
I have 2 Stories complete
**Day 2**
We have to add more resources
You had a chat with Falon and Isha
Story 2 is still incomplete
**Day 3**
Thanks for having Chat with Isha.
Conflict Resolution done between Remo and Amit
Story 2 completed. Moving to Story 3
<input type="text" onChange={(e) => this.setState({inputValue: e.target.value})} value={this.state.inputValue} />
函数可以使用state中的值,而不使用refs。提交后不会删除该值,因此您可以在需要时重复使用它。
有关受控和非受控组件的更多信息,请参阅:https://medium.com/@peter.yun.kim/controlled-and-uncontrolled-input-values-in-react-907119cc98d4