简体   繁体   English

更改部分数据后重新渲染状态-reactjs

[英]re-render the state after changing a part of the data - reactjs

I have state here of list which contains an array of objects: 我在此处的列表状态包含对象数组:

this.state = {
  list: [{test: 2}, {test33: 4}]
}

I created a function to change the number (2nd value in the object) if I found an identical name (1st value in the object). 如果发现相同的名称(对象中的第一个值),我创建了一个函数来更改数字(对象中的第二个值)。 However I am not sure how can I re-render my component then to see my updated state. 但是,我不确定如何重新渲染组件然后查看更新后的状态。

updateData(item1, item2){
    if (!item1 || !item2) {
      return 'Enter valid item1 or item2 to add item';
    }

    var hasBeenFound = false;

    this.state.list.forEach(function (item) {
        if (item.item1 === item1) {
            hasBeenFound = true;
           item.item2 = item2;
        }
    });

    if(!hasBeenFound){
      this.setState((prevState) => ({
        list: prevState.list.concat({item1: item1, item2: item2})
      }));
    }

  }

For some reason even though it found some identical item1 it wont re-render the item2 even though I asign it to the new value. 由于某种原因,即使它找到了一些相同的item1,即使我将其分配给新值,它也不会重新渲染item2。 Do i need to use lifecycle function? 我需要使用生命周期功能吗? Please help! 请帮忙! newbie here! 新手在这里!

The problem this code mutates (changes in place) state specifically this line item.item2 = item2; 该代码特别是更改此行item.item2 = item2;状态的item.item2 = item2;

this.state.list.forEach(function (item) {
        if (item.item1 === item1) {
            hasBeenFound = true;
           item.item2 = item2;
        }
    });

The reason forEach passes a reference to each object of the array, so any change to this object changes original array (and thus changes state). 其原因forEach传递到阵列中的每个对象的参考,所以任何改变到该对象改变原始阵列(和因而改变状态)。
Better approach is to use setState method like this 更好的方法是像这样使用setState方法

 if(this.state.some(item => item.item1 === item1){
    hasBeenFound = true;
    this.setState(prevState => ({
       list: prevState.list.map(item => {
         if(item.item1 === item1) return {...item, item2: item2};
         return item;
       })
 }

This code can be improved more, i've just added the minimum change that will make it work. 可以进一步改进此代码,我刚刚添加了使它起作用的最小更改。

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

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