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

时间:2017-04-22 03:24:03

标签: javascript html reactjs components jsx

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

我遇到的问题是在踢“关闭”按钮时重置状态,以便盒子呈现原始形状和不透明度。我在“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()} />
      }
    )
  }
}

请帮忙!为什么该死的状态不会改变回来?!?!

1 个答案:

答案 0 :(得分:1)

有一些问题...... .map返回一个新数组,它不会改变现有状态。因此,您需要将其分配给变量以查看更改。

此外,您必须返回.map中的值,或使用"implicit" return ({ vs {

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

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

&#13;
&#13;
  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
      }]}
    ]}
  }
&#13;
&#13;
&#13;