最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Error: "Cannot update during an existing state transition" - Stack Overflow

programmeradmin3浏览0评论

I am trying to write an application that uses a toastr ponent. However, when I try and dispatch a redux action in this ponent I get the following console message:

Warning: Cannot update during an existing state transition (such as within render or another ponent's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to ponentWillMount.

You can see an example of this in this codesandbox. Particularly, the issue is at the toastr.js ponent at line 23. Thanks!

I am trying to write an application that uses a toastr ponent. However, when I try and dispatch a redux action in this ponent I get the following console message:

Warning: Cannot update during an existing state transition (such as within render or another ponent's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to ponentWillMount.

You can see an example of this in this codesandbox. Particularly, the issue is at the toastr.js ponent at line 23. Thanks!

Share asked Jan 16, 2019 at 17:18 JimmyJimmy 3,90016 gold badges51 silver badges111 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

The problem is exactly what the error message says: you're triggering a form of React state update directly inside of a render() method:

const Toasts = ({ appointments, resetState, toastedAppointment, toasts }) => {
  if (toasts.type) {
    switch (toasts.type) {
      case "dataFetched":
        resetState(); // Dispatching this action creates the warning.

In this case it's dispatching a Redux action, but that ultimately results in a React setState() call.

Don't do that :) Side effect logic, like triggering some kind of additional update based on current state, should probably happen in something like ponentDidUpdate. The Toasts ponent would probably need to be converted from a function ponent to a class ponent accordingly.

发布评论

评论列表(0)

  1. 暂无评论