1

我必须使用键找到所有状态值,并在下面的嵌套状态中style更改值。red

this.state = {
  front: {
    line1: {
      style: "blue",
      name: "name1"
    },
    line2: {
      style: "blue",
      name: "name2"
    }
  }
}

我做了如下尝试,但它给出了错误。

Object.keys(this.state).forEach(function(k,prevState) {
  this.setState(prevState => ({ [k]:
        {...prevState[k], style: "red"} 
  }))
});

我该如何更新它?

4

5 回答 5

5

您可以Object.keysfront对象上使用来获取包含所有键名的数组,然后reduce在其上使用并构建一个新front对象,在其中将所有style属性更改为"red".

class App extends React.Component {
  state = {
    front: {
      line1: {
        style: "blue",
        name: "name1"
      },
      line2: {
        style: "blue",
        name: "name2"
      }
    }
  };

  onClick = () => {
    this.setState(({ front }) => ({
      front: Object.keys(front).reduce((acc, key) => {
        acc[key] = {
          ...front[key],
          style: "red"
        };
        return acc;
      }, {})
    }));
  };

  render() {
    return (
      <div>
        <button onClick={this.onClick}>Change to red</button>
        <div>{JSON.stringify(this.state)}</div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

于 2019-04-11T14:43:20.023 回答
0

你有问题,因为你不使用箭头功能。您应该使用数组函数来访问setState

Object.keys(this.state).forEach((k,prevState) => {
  this.setState(prevState => ({ [k]:
        {...prevState[k], style: "red"} 
  }))
});
于 2019-04-11T14:43:13.047 回答
0

只需复制状态,然后循环遍历它并更改样式键的值并更新状态

let copy = JSON.parse(JSON.stringify(this.state))
Object.keys(copy).forEach(e=>{
  copy[key].style = 'red'
})
this.setState(copy)
于 2019-04-11T14:45:53.823 回答
0

出现问题是因为您在 forEach 回调中使用了 ES5 函数,这意味着回调具有函数范围,其中this指的是回调函数的上下文。

解决方案 1:使用 ES6 箭头函数。箭头函数具有定义它的范围。

Object.keys(this.state).forEach((k) => {
   this.setState({ [k]: {...this.state[k], style: 'red' }})
});

解决方案2:使用绑定方法。

bind() 方法创建一个新函数,在调用该函数时,会将其 this 关键字设置为提供的值。

Object.keys(this.state).forEach(function(k) {
   this.setState({ [k]: {...this.state[k], style: 'red' }})
}.bind(this));
于 2019-04-11T14:46:22.187 回答
0

我建议制定一种在该州设置红色样式的方法。您可以复制并粘贴下面的代码并根据自己的喜好进行编辑。

setRedStyles = () => {
  const newState = { ...this.state };
  Object.keys(newState.front).forEach(prop => {
    if (newState.front[prop].style) {
      newState.front[prop].style = "red";
    }
    this.setState(newState);
  });
}

您应该能够在 onClick 函数中调用 setRedStyles() 直接调用此函数。

于 2019-04-11T15:25:58.290 回答