在 React.js 中设置和重置状态

Setting and resetting states in React.js

我正在尝试在我的网页中构建一个部分,其中有四个组件显示在 2X2 网格中。单击其中一个时,框会扩展到屏幕中央,而其他框会淡出。我已经通过在几个不同的属性上调用 setState 来切换 css 类 来解决这部分问题。

我遇到的问题是在 "close" 按钮被踢出时重置状态,以使框呈现其原始形状和不透明度。我在 "handleCloseClick" 函数中看到一个 console.log,所以我知道它是有线的 属性。无论我如何遍历状态数组,我都无法将它们的属性更改回原始状态。这是我的代码。

class Parent extends Component{
  constructor(){
    super();
    this.state = 
      attrs: {[{
        id: 1,
        expand: false,
        reduced: false,
        seeText: false
    }],
    [{
        id: 2,
        expand: false,
        reduced: false,
        seeText: false
    }],
    [{
        id: 3,
        expand: false,
        reduced: false,
        seeText: false
    }],
    [{
        id: 4
        expand: false,
        reduced: false,
        seeText: false
    }]}
    this.handleClick = this.handleClick.bind(this)
    this.handleCloseClick = this.handleClick.bind(this)
  }
  /*This function works*/
  handleClick(e){
    const array = this.state.attrs
    array.map(function(element){
      if(element.id === i){
        element.reduced = false;
        element.expand = true;
        element.seeText = true;
      }else{
        element.reduced = true;
      }
    })
    this.seState({attrs: array})
  }
  /*This function will console.log but will not setState of attrs*/
  handleCloseClick(){
    const newArray = this.state.attrs
    newArray.map(function(element(){
      element.expand = false;
      element.reduced = false;
      element.seeText = false;
    })
    this.setState(attrs: newArray})
  }
  render(){
    const newEls = this.state.attrs;
    return(
      {newEls.map(function(newEl, index)){
        return <Child key={index} onClick={this.handleClick(el)} onCloseClick={this.handleCloseClick()} />
      }
    )
  }
}

请帮忙!那该死的状态怎么变不回来了?!?!

有一些问题... .map return是一个新数组,它不会更改现有状态。所以需要赋值给一个变量才能看到变化。

此外,您必须 return .map 中的值,或者使用 ({{

handleCloseClick(){
  const newArray = this.state.attrs.map(element => ({
    element.expand = false;
    element.reduced = false;
    element.seeText = false;
  }))
  this.setState(attrs: newArray})
}

您也可以将初始状态移动到它自己的方法中,然后在构造函数中使用,当您想要重置它时...

  constructor() {
  ...
    this.state = this.initialState();
  }
  
  close() {
    this.setState(this.initialState());
  }
  
  initialState() {
    return {
      attrs: [
      [{
          id: 1,
          expand: false,
          reduced: false,
          seeText: false
      }],
      [{
          id: 2,
          expand: false,
          reduced: false,
          seeText: false
      }],
      [{
          id: 3,
          expand: false,
          reduced: false,
          seeText: false
      }],
      [{
          id: 4
          expand: false,
          reduced: false,
          seeText: false
      }]}
    ]}
  }