【发布时间】:2019-02-22 19:49:30
【问题描述】:
每当我输入内容时,搜索栏都会更新状态,它会跳过第一个字母。例如,如果我写“asdf”,它只会显示“sdf”。
我在这行代码之前试过console.log
this.props.newQuery(this.state.newSearchQuery);
一切正常。
请检查下面的 App.js 和 SearchBar.js 代码
谢谢
App.js
import React from 'react';
import SearchBar from './components/SearchBar';
class App extends React.Component {
constructor(){
super();
this.state = {
searchQuery: '',
fetchedData: []
};
}
newQuery(query){
this.setState({
searchQuery: query
});
}
onSearch(){
const userInput = this.state.searchQuery;
if(userInput !== '' && userInput !== ' '){
const API_KEY = `https://pokeapi.co/api/v2/pokemon/${userInput}`;
fetch(API_KEY, {
method: 'GET',
headers: {
Accept: 'application/json'
}
})
.then(result => result.json())
.then(data => this.setState({ fetchedData: data.results }));
console.log('res', this.state.fetchedData);
}
}
render(){
return(
<div className="App">
<h2>Search Pokemos by Types</h2>
<hr />
<SearchBar onSearch={this.onSearch.bind(this)} newQuery={this.newQuery.bind(this)} />
</div>
);
}
}
export default App;
搜索栏.js
import React from 'react';
class SearchBar extends React.Component {
constructor(props){
super(props);
this.state = {
newSearchQuery: '' //this blank value get executed first when i console.log
}
}
searchInput(event){
this.setState({
newSearchQuery: event.target.value
});
this.props.newQuery(this.state.newSearchQuery);
console.log(this.state.newSearchQuery); // if i log "asdf", state on top "newSearchQuery" skips the first letter, a and shows "sdf" only.
}
render(){
return(
<div className="input-group">
<input onChange={this.searchInput.bind(this)} className="form-control" placeholder="[eg. Ditto, Cheri, etc]" />
<button onClick={this.props.onSearch} className="btn btn-success">Search</button>
</div>
);
}
}
export default SearchBar;
【问题讨论】:
-
不发图片,发真实代码。
-
添加了代码。谢谢
-
您的意思是
console.log(this.state.newSearchQuery);记录错误? -
是的,它会跳过字符串的第一个字母。例如,当它应该记录“USA”时,它只通过跳过“U”来记录“SA”。
-
要知道,
setState在第二个参数中有一个回调,它将在状态更新后发生。setState({ name: "Michael" }, () => console.log(this.state));
标签: javascript reactjs setstate