我有一个输入字段,用于过滤数组中的元素。
搜索结果总是落后一次击键,我猜是因为 setState 不会立即更新 View ?解决这个问题的最佳方法是什么?
class App extends Component {
constructor() {
super();
this.state = {
images:[],
searchfield: '',
filteredImages:[],
suggestedKeywords:[],
inputValue: ''
}
}
onSearchChange = (event) => {
this.setState({searchfield: event.target.value});
this.setState({inputValue: event.target.value});
let filteredImages = this.state.images.filter(image => {
return image.labels.includes(this.state.searchfield.toLowerCase());
});
console.log(event.target.value);
this.setState({filteredImages});
}
}
const SearchBox = ({searchfield, searchChange, inputValue}) => {
return (
<div>
<input
type="search"
value={inputValue}
onChange={searchChange}
placeholder="Search images..."
/>
</div>
);
}
最佳答案
The search results are always one keystroke behind, I assume because setState doesn't instantly update the view? What's the best way to work around that?
这不是问题。
您的问题是您假设 setState 的更新会立即发生。
this.setState({searchfield: event.target.value}); //You update searchfield here
return image.labels.includes(this.state.searchfield.toLowerCase());
//but this.state.searchfield doesn't reflect the update yet!
因此,只需使用更新后的值而不是商店中的值即可。
return image.labels.includes(event.target.value.toLowerCase());
关于javascript - React setState 不立即更新组件 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51124711/