我怎么没有在ReactJS中更新状态变量? [英] How am I failing to update a state variable in ReactJS?

查看:117
本文介绍了我怎么没有在ReactJS中更新状态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ReactJS中设置了一个事件处理程序,以便当有人单击日历条目的完成复选框时,日历条目仍然在系统中,但它被标记为隐藏为不显示的内容。 (日历用于允许一次性和重复出现的条目,并允许标记此实例完成和隐藏此系列选项以用于重复输入条目,但此细节在此不涉及我。)

I have an event handler in ReactJS designed so that when someone clicks the "Done" checkbox for a calendar entry, the calendar entry is still in the system but it is marked hidden as something not to show. (The calendar is made to allow both one-off and recurring entries, and allow both "Mark this instance done" and "Hide this series" options for recurring entries, but this detail does not concern me here.)

我的事件处理程序用于复制 this.state 中的数组,进行克隆, push() es一个项目,并将变异的克隆保存为一个可能很麻烦的解决方法,直接 push()将项目添加到<$ c $下的数组中C> this.state 。根据包含的 console.log()语句,我似乎成功获取了该项(一个整数,此处等于 1 ),成功克隆一个now-empty数组并将 push()整数输入克隆数组,然后无法修改空 this.state.hidden_​​entries

My event handler is intended to copy an array in this.state, makes a clone, push()es an item, and saves the mutated clone as a perhaps cumbersome workaround for directly push()ing an item to an array under this.state. Based on the included console.log() statements, it appears that I am successfully obtaining the item (an integer, here equal to 1), successfully cloning a now-empty array and push()ing the integer into the cloned array, and then failing to modify the empty this.state.hidden_entries.

我的代码为:

    hide_instance: function(eventObject) {
      console.log(eventObject);
      var id = parseInt(eventObject.target.id.split('.')[1]);
      console.log(id);
      // var id = eventObject.target.id;
      console.log(this.state.hidden_instances);
      console.log('Cloned: ');
      var hidden_instances = clone(this.state.hidden_instances);
      console.log(hidden_instances);
      hidden_instances.push(id);
      console.log('Before setState()');
      console.log(hidden_instances);
      this.setState({'hidden_instances': hidden_instances});
      console.log(this.state.hidden_instances);
      console.log('After setState()');
      this.forceUpdate();
    },

在我的 console.log()输出我有:

site.js:350 SyntheticEvent {dispatchConfig: Object, dispatchMarker: ".0.3.2:1.1.0.0.0", nativeEvent: MouseEvent, type: "click", target: input#hide-2015-9-18.1.hide-instance…}
site.js:352 1
site.js:354 []
site.js:355 Cloned: 
site.js:357 []
site.js:359 Before setState()
site.js:360 [1]
site.js:362 []
site.js:363 After setState()

My console.log()语句按顺序说在setState()之前,记录变异克隆,尝试将变异克隆分配给 this.state.hidden_​​instances ,然后读回刚刚设置的状态变量,只是为了看它保持不变。

My console.log() statements in order say "Before setState()", log the mutated clone, attempt to assign the mutated clone the correct way to this.state.hidden_instances, and then reads back the state variable that was just set, only to see that it remains unchanged.

什么应该在这种情况下,我会采用不同的方式将项目附加到this.state.hidden_​​instances,为什么我的代码无法改变该位置的值?

What should I be doing differently, in this case, to append an item to this.state.hidden_instances, and why is my code failing to mutate the value at that location?

- UPDATE -

--UPDATE--

我将发布clone()函数,仅用于JSON可序列化对象,但它似乎是给定一个空数组时返回一个空数组;我能看到问题的唯一方法是它返回相同的空数组而不是新的数组。但是如果我错过了什么,这里是:

I'll post the clone() function, intended for JSON-serializable objects only, but it appears to be returning an empty array when given an empty array; the only way I can see a problem is if it's returning the same empty array instead of a new one. But in case I missed something, here it is:

  var clone = function(original) {
    if (typeof original === 'undefined' ||
      original === null ||
      typeof original === 'boolean' ||
      typeof original === 'number' ||
      typeof original === 'string') {
      return original;
    }
    if (Object.prototype.toString.call(original) === '[object Array]') {
      var result = [];
      for(var index = 0; index < original.length; index += 1) {
        result[index] = clone(original[index]);
      }
    } else {
      var result = {};
      for(var current in original) {
        if (original.hasOwnProperty(current)) {
          result[current] = original[current];
        }
      }
    }
    if (typeof original.prototype !== 'undefined') {
      result.prototype = original.prototype;
    }
    return result;
  }


推荐答案

来自文档(尽管在一个大红色框中):

From the documentation (in a big red box nonetheless):

setState()不会立即改变 this.state 但会创建待定状态过渡。调用此方法后访问 this.state 可能会返回现有值。

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.


第二个(可选)参数是一个回调函数,将执行一次 setState 已完成且组件已重新呈现。

The second (optional) parameter is a callback function that will be executed once setState is completed and the component is re-rendered.

该回调将通过更新状态afaik。

That callback gets passed the updated state afaik.

这篇关于我怎么没有在ReactJS中更新状态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆