如何在ReactJS中使用嵌套状态中的所有特定键更改值

问题描述 投票:1回答:5

我必须使用键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"} 
  }))
});

我该如何更新?

javascript reactjs
5个回答
5
投票

您可以在Object.keys对象上使用front来获取包含所有键名的数组,然后在其上使用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>

0
投票

你有问题,因为你没有使用箭头功能。你应该使用数组函数来访问qazxsw poi

setState

0
投票

只需制作一个状态的副本,然后循环遍历它,并更改样式键的值并更新状态

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

0
投票

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

let copy = JSON.parse(JSON.stringify(this.state))
Object.keys(copy).forEach(e=>{
  copy[key].style = 'red'
})
this.setState(copy)

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


0
投票

您的问题发生是因为您在forEach回调中使用了ES5函数,这意味着回调函数具有函数作用域,其中setRedStyles = () => { const newState = { ...this.state }; Object.keys(newState.front).forEach(prop => { if (newState.front[prop].style) { newState.front[prop].style = "red"; } this.setState(newState); }); } 指的是回调函数的上下文。

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

this

解决方案2:使用Object.keys(this.state).forEach((k) => { this.setState({ [k]: {...this.state[k], style: 'red' }}) }); 方法。

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

bind
© www.soinside.com 2019 - 2024. All rights reserved.