简体   繁体   English

变量值未在函数中更新

[英]Variable value doesn't update in function

I'm using an onClick handler in a stateless React Component. 我在无状态React组件中使用onClick处理程序。
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. 在div上触发click事件时,它会触发loadMore操作,该操作使用redux操作从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. 我的问题是由于redux动作, count没有更新。 If I remove it, count is updating properly. 如果我删除它, count正在正确更新。

Why a redux action (which is correctly working) stops count from updating ? 为什么redux动作(正常运行)会停止更新count

Thanks 谢谢

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

React only reacts to updates on your state or props. React只对您的状态或道具的更新做出反应。 From the code you have shared, it does not seem like count is part of any state. 从您共享的代码来看, count似乎不是任何状态的一部分。 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. 将您的组件转换为常规组件,并定义state = { count: 0}并在“ loadMore”事件中使用setState对其进行更新。 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. 将count移至redux状态,并使用mapStateToProps将其映射到属性,最后,通过redux reducer而不是在'loadMore'事件中更新count。 See updating state in redux 查看redux中的更新状态

Edit: a better example for #2 Change state onClick React+Redux 编辑:#2 更改状态onClick React + Redux的更好示例

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

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