javascript - React setState 不立即更新组件 View

标签 javascript reactjs state

我有一个输入字段,用于过滤数组中的元素。

搜索结果总是落后一次击键,我猜是因为 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/

相关文章:

javascript - 从窗口中选择的文本为空

javascript - 更改不透明度属性并将渐变应用于 Bootstrap 工具提示

javascript - 从动态生成的表单中响应访问状态,多层次深度

javascript - 如何遍历 localStorage 值

javascript - 警告 : Unknown DOM property class. 你是说类名吗?

python - 在函数式编程(或其他方式)中递归时,使用显式状态变量的好处/限制是什么?

python - 如何在没有类的情况下在 Python 中维护状态?

javascript正则表达式,拆分用户的全名

javascript - onfocusout/onfocusin 不工作

reactjs - 类型错误 : this is undefined?