通过键插值和销毁从状态对象删除属性

时间:2019-03-15 13:52:00

标签: javascript reactjs

当我尝试根据foo变量的值从状态对象中删除属性时

...
const [state, setState] = useState(initialState);
...
const {[foo], ...newState} = state;
setState({newState});

我得到了这个SyntaxError

Parsing error: Unexpected token , // the one after [foo]

3 个答案:

答案 0 :(得分:4)

您不能像这样破坏动态键,并且用丢失的键更新状态将使该键保持不变,因此不会将其从状态中删除。

您可以将状态变量设置为undefined,以将其从状态中删除。

示例

class App extends React.Component {
  state = {
    foo: "Foo",
    bar: "Bar"
  };

  deleteStateVariable = param => {
    this.setState(prevState => {
      const state = { ...prevState };
      state[param] = undefined;
      return state;
    });
  };

  render() {
    return (
      <div>
        <div>{JSON.stringify(this.state)}</div>
        <button onClick={() => this.deleteStateVariable("foo")}>
          Delete Foo
        </button>
        <button onClick={() => this.deleteStateVariable("bar")}>
          Delete Bar
        </button>
      </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>

如果使用的是钩子,则传递给setState的参数将完全替换当前状态,因此您可以对不需要的键进行解构。

示例

const { useState } = React;

function App() {
  const [state, setState] = useState({
    foo: "Foo",
    bar: "Bar"
  });

  function deleteStateVariable(param) {
    const { [param]: tmp, ...rest } = state;
    setState(rest);
  }

  return (
    <div>
      <div>{JSON.stringify(state)}</div>
      <button onClick={() => deleteStateVariable("foo")}>Delete Foo</button>
      <button onClick={() => deleteStateVariable("bar")}>Delete Bar</button>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

答案 1 :(得分:3)

我认为您可以这样编写动态结构:

let tmpVal = "" 
const {[foo]: tmpVal, ...state} = this.state;
this.setState({state});

但是它不会从状态中删除该属性。

答案 2 :(得分:1)

聚会晚了一点,但是如果有人不满意答案,这就是我的两分钱。

setData((prevData) => {
  const newData = {...prevData}
  delete newData["key_here"]
  return newData;
})