【发布时间】:2021-01-07 14:45:49
【问题描述】:
我创建了两个输入,并使用setState 更新了状态。当我输入输入然后console.log 它不会立即记录它。
例如,如果我在输入中键入“an”,它将在第二次击键时控制台记录“a”...
我知道this.setState 不会立即更新并批量更新状态,但是当我过去这样做时它已经工作了。 Why isn't my input value updating with React?
如何让我的输入立即更新?我希望这种情况发生,因为我需要使用用户输入作为搜索关键字并将每个输入值传递给函数。
代码:
export default class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
movieTitleSearch: "",
searchByYear: "",
};
}
handleOnChange = (event) => {
const { movieTitleSearch } = this.state;
const { searchByYear } = this.state;
this.setState({
...this.state, [event.target.name]: event.target.value,
},
() => {
if (movieTitleSearch || searchByYear > 1) {
this.props.movieSearch(movieTitleSearch, searchByYear);
}
console.log(movieTitleSearch) // does not update straight away in the console.
console.log(searchByYear) // does not update straight away in the console.
}
);
};
render() {
return (
<div>
<label>search film title</label>
<input
onChange={this.handleOnChange}
type="text"
name="movieTitleSearch"
placeholder="search by film"
value={this.state.movieTitleSearch}
/>
<label>search by year</label>
<input
onChange={this.handleOnChange}
type="text"
name="searchByYear"
placeholder="search by year"
value={this.state.searchByYear}
/>
</div>
);
}
}
更新的 ONCHANGE 函数
handleOnChange = (event) => {
const { movieTitleSearch } = this.state;
const { searchByYear } = this.state;
this.setState(
{
...this.state, [event.target.name]: event.target.value,
},
);
this.props.movieSearch(this.state.movieTitleSearch, this.state.searchByYear)
console.log(this.state.movieTitleSearch) // why when i type in the inputs does this not log to the console straight away?
console.log(this.state.searchByYear)
};
【问题讨论】:
标签: javascript reactjs input