为什么在我输入时React文本/输入字段中没有显示任何内容



我使用的是React 16.13.0。我想构建一个简单的搜索组件,在用户输入时进行搜索。我创造了/src/components/Search.jsx

import React, { Component } from "react";
export default class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchTerm: "",
setSearchTerm: "",
searchResults: [],
setSearchResults: []
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
console.log("value:" + event.target.value);
this.state.searchTerm = event.target.value;
fetch('/coops/?contains=' + encodeURIComponent(this.state.searchTerm),{
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
}).then(response => {
this.state.searchResults = response;
});
}
render() {
return (
<div className="searchForm">
<input
type="text"
placeholder="Search"
value={this.state.searchTerm}
onChange={this.handleChange}
/>
<ul>
{this.state.searchResults.map(item => (
<li>{item}</li>
))}
</ul>
</div>
);
}
}

我遇到的问题是,在渲染组件之后,当我键入时,搜索框中不会显示任何内容。我确实看到了针对端点执行的请求,每个请求都包含我试图键入的字母。如有任何关于如何在键入时将整个搜索词显示在文本字段中的帮助,我们将不胜感激。

替换此:

this.state.searchTerm = event.target.value;

这个:

this.setState({searchTerm: event.target.value})

搜索结果:

this.setState({searchResults: response})

最新更新