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

Har*_*esh 1 javascript reactjs

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

this.state = {
  front: {
    line1: {
      style: "blue",
      name: "name1"
    },
    line2: {
      style: "blue",
      name: "name2"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

我该如何更新?

Tho*_*lle 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"));
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)