Hỏi về event trong React

Chào mọi người! Em đang học React và có thắc mắc về đoạn code sau:
#App.js

import React from 'react';
import CardList from './CardList';
import SearchBox from './SearchBox';
import { robots } from './robots';

class App extends React.Component{
	constructor(){
		super();
		this.state = {
			robots: robots,
			searchField: '',
			filteredRobots: robots
		}
		this.onSearchChange = this.onSearchChange.bind(this);
	}

	onSearchChange(event){
		this.setState({
			searchField: event.target.value
		});
		//====================
		const filteredRobots = this.state.robots.filter(robots => {
			return robots.name.toLowerCase().includes(this.state.searchField.toLowerCase());
		});
		console.log(filteredRobots);
		//====================
	}

	render(){
		return(
			<div className='tc'>
				<h1>RoboFriends</h1>
				<SearchBox onChange={this.onSearchChange} searchField={this.searchField}/>
				<CardList robots={filteredRobots} />
			</div>
		);
	}
}

export default App;

#SearchBox.js

import React from 'react';

class SearchBox extends React.Component{
	render(){
		return(
			<div className='pa2'>
				<input
					className='pa3 ba b--green bg-lightest-blue'
					type='search'
					placeholder='search robots'
					onChange={this.props.onChange} 
				/>
			</div>
		);
	}
}

export default SearchBox;

Thì khi em gõ vào searchBox. filteredRobots cứ cập nhật trễ, ví dụ e đã gõ “ca” thì filteredRobots chỉ mới lọc theo “c” và in ra console.
Sửa App.js lại thành

import React from 'react';
import CardList from './CardList';
import SearchBox from './SearchBox';
import { robots } from './robots';

class App extends React.Component{
	constructor(){
		super();
		this.state = {
			robots: robots,
			searchField: '',
			filteredRobots: robots
		}
		this.onSearchChange = this.onSearchChange.bind(this);
	}

	onSearchChange(event){
		this.setState({
			searchField: event.target.value
		});
		
	}

	render(){
        //====================
		const filteredRobots = this.state.robots.filter(robots => {
			return robots.name.toLowerCase().includes(this.state.searchField.toLowerCase());
		});
		console.log(filteredRobots);
		//====================
		return(
			<div className='tc'>
				<h1>RoboFriends</h1>
				<SearchBox onChange={this.onSearchChange} searchField={this.searchField}/>
				<CardList robots={robots} />
			</div>
		);
	}
}

export default App;

thì fillteredRobots không còn bị cập nhật trễ nữa. Mong mọi người giải thích giúp em! Em xin cảm ơn

1 Like

Em hiểu tại sao rồi ạ!

1 Like

Theo rì quét

2 Likes
2 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?