简体   繁体   English

如何工作 setState function?

[英]How to works setState function?

I want to create a basic crud app.我想创建一个基本的 crud 应用程序。 So i want to create a basic live search.所以我想创建一个基本的实时搜索。 For this reason, i have written a simple code.为此,我编写了一个简单的代码。 Like this像这样

searchProduct = (e) => {
 const query = e.target.value.toLowerCase();
 const data = [...this.state.exampleProducts];
 const filteredData = data.filter(p => {
 return p.name.toLowerCase().includes(query);
})
 console.log(filteredData);
}

When I use the setState function, the console.log output gives different results.当我使用 setState function 时,console.log output 给出了不同的结果。

guessing you are new in Reactjs, please check this one first https://css-tricks.com/understanding-react-setstate/猜你是 Reactjs 的新手,请先检查这个https://css-tricks.com/understanding-react-setstate/

Do not depend on this.state immediately after calling setState() and make use of the updater function instead.不要在调用 setState() 后立即依赖 this.state 并使用更新程序 function 代替。

setState has a callback function that you can use, but DO NOT use setState inside of it. setState有一个可以使用的回调 function,但不要在其中使用 setState。

When I need to log something inside the state, prefer to use console.log in the render function in this way you won't miss anything.当我需要在 state 中记录某些内容时,更喜欢在渲染 function 中使用 console.log,这样您就不会错过任何内容。

The setState dose doesn't apply the change immediately. setState 剂量不会立即应用更改。 You can pass callback function like this:您可以像这样传递回调 function :

 this.setState({value: 'updated-value'}, () => { console.log(this.state.value); // updated-value // You can use your updated state here })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM