地图未返回对象的正确数组

时间:2018-12-03 01:12:28

标签: javascript reactjs ecmascript-6

试图做一个映射来将selected的值设置为true和false,但是它不会改变现有的true值,这是怎么回事?

selectTab = tab => e => {
    const { data } = this.state;
    this.setState(
      {
        data: data.map(o =>
          o.tab === tab ? { selected: true, ...o } : { selected: false, ...o }
        )
      },
      () => console.log(this.state.data)
    );
  };

https://codesandbox.io/s/885l8q537l

1 个答案:

答案 0 :(得分:2)

首先尝试扩展对象,然后添加selected属性。否则,selected中的o属性每次都会覆盖它。

selectTab = tab => e => {
  this.setState(
    prevState => ({
      data: prevState.data.map(o =>
        o.tab === tab ? { ...o, selected: true } : { ...o, selected: false }
      )
    }),
    () => console.log(this.state.data)
  );
};

class App extends React.Component {
  state = {
    data: [
      {
        tab: 1,
        content: "Tab 1 content",
        selected: true
      },
      {
        tab: 2,
        content: "Tab 2 content"
      },
      {
        tab: 3,
        content: "Tab 3 content"
      }
    ]
  };

  selectTab = tab => e => {
    this.setState(
      prevState => ({
        data: prevState.data.map(o =>
          o.tab === tab ? { ...o, selected: true } : { ...o, selected: false }
        )
      }),
      () => console.log(this.state.data)
    );
  };
  
  render() {
    const { activeTab, data } = this.state;
    return (
      <div>
        {data.map(obj => (
          <div onClick={this.selectTab(obj.tab)}>{obj.tab}</div>
        ))}
        {data.map(obj => (
          <div>{obj.selected && obj.content}</div>
        ))}
      </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>