简体   繁体   中英

Variable value doesn't update in function

I'm using an onClick handler in a stateless React Component.
When a click event is triggered on a div, it fires the loadMore action who uses a redux action to fetch more data from a REST API.

count = 6;

var loadMore = e => {
 getArticlesComments(article.slug, count, count + 2);
 count = count + 6;
};

My issue is that count isn't updating because of the redux action. If I remove it, count is updating properly.

Why a redux action (which is correctly working) stops count from updating ?

Thanks

您需要先将计数放入状态,然后再更新状态

React only reacts to updates on your state or props. From the code you have shared, it does not seem like count is part of any state. If you want your view to update when count changes, then count needs to be within a state. You mentioned that your component is stateless so you either need to:

  1. Convert your component to a regular component and define state = { count: 0} and update it with setState in your 'loadMore' event. See example
  2. Move count to your redux state and map it to a property using mapStateToProps and, finally, update count via your redux reducer and not in your 'loadMore' event. See updating state in redux

Edit: a better example for #2 Change state onClick React+Redux

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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