取消以保持以前的状态不起作用

时间:2019-05-03 06:15:48

标签: reactjs state reset

我已应用并取消了带有复选框列表的按钮。 单击“应用”后,所选/选中的值应存储在状态prevVal变量中。 选中其他复选框并单击“取消”后,应使该复选框填充prevVal

但是点击取消后,currentValue就会被填充。

我正在使用一个临时变量来保存句柄复选框事件的当前状态。

将值推送到临时变量后,我的状态将自动更新为该临时值。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

我认为这就是您要寻找的:) 如果您想查看功能,这里也是沙箱:https://stackblitz.com/edit/react-pmdgir?file=index.js

import React, { Component } from 'react';
import { render } from 'react-dom';

export default class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      prevVal: [],
      currentVal: [],
      filter: [
        {
          key: 'a'
        },
        {
          key: 'b'
        },
        {
          key: 'c'
        }
      ]
    }
  }

  toggleCurrentVal = (key) => {
    const currentVal = this.state.currentVal
    const beforeSlicedVal = []

    if(currentVal.includes(key)){
      currentVal.splice(currentVal.indexOf(key), 1)
    } else {
      currentVal.push(key)
    }
    this.setState((prevState) => {
      const prevStateValue = prevState.prevVal.length <= currentVal.length ? prevState.currentVal.filter((val) => val !== key) : prevState.prevVal
      return {
         currentVal: currentVal.sort(),
         prevVal: prevStateValue
      }
    }, () => console.log("currentValue:"+ this.state.currentVal + " preValue: " + this.state.prevVal ))
  }

  applyFilter = () => {
      console.log("currentValue:"+ this.state.currentVal + " preValue: " + this.state.prevVal )
  }

  cancel = () => {
    this.setState({
      currentVal: [],
      prevVal: this.state.currentVal
    }, () => console.log("currentValue:"+ this.state.currentVal + " preValue: " + this.state.prevVal ))
  }

  render() {
    let checkboxes = [];
    let checkedValues = this.state.currentVal
    if (this.state.filter) {
      this.state.filter.map(data => {
        checkboxes.push(
          <div><input type="checkbox" checked={checkedValues.includes(data.key)}name="a" value={data.key} onClick={() => this.toggleCurrentVal(data.key)}></input></div>
        )
      })
    }
    return (
      <div>
        {checkboxes}
        <button onClick={this.applyFilter}>Apply</button>
        <button onClick={this.cancel}>Cancel</button>
      </div>)
  }
}


render(<App />, document.getElementById('root'));