ReactJS - 在状态

时间:2017-10-25 16:44:52

标签: reactjs react-native ecmascript-6

我在州有两个清单:

this.state = {
  fisrtList: [],
  secondList: [],
}

我想要的是切换这些列表,我的意思是:

const tmp = [];
tmp = fisrtList;
fisrtList = secondList;
secondList = tmp;

由于设置状态会导致渲染,因此不起作用。它只是改变其中一个。我使用了不同的方法,例如将tmp保持在州内,但它也没有用。

您是否有任何建议正确切换这两个列表?

2 个答案:

答案 0 :(得分:3)

使用切换参考设置新状态。由于我们正在更改引用,因此无需克隆它们。

注意:我使用了setState的updater callback option

this.setState(({ fisrtList, secondList }) => ({
  fisrtList: secondList,
  secondList: fisrtList
}));

<强>演示:

&#13;
&#13;
class App extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      fisrtList: [1, 2, 3],
      secondList: ['a', 'b', 'c']
    };
  }
 
  toggle = () => this.setState(({ fisrtList, secondList }) => ({
    fisrtList: secondList,
    secondList: fisrtList
  }));
  
  render() {
    const { fisrtList, secondList } = this.state;
    
    return (
      <div>
        <button onClick={this.toggle}>Toggle</button>
      
        <div>{fisrtList.join(',')}</div>
        
        <div>{secondList.join(',')}</div>
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  demo
);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="demo"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

制作一个如下所示的切换方法:

toggle = () => {
   this.setState({
       fisrtList: this.state.secondList,
       secondList: this.state.fisrtList
    });
}

render() {
   return <button onClick={this.toggle}>Toggle the lists</button>
}