React - 跨父母持久化元素

时间:2017-08-21 09:03:02

标签: javascript reactjs

有没有办法避免在父项之间移动元素时卸载/重新安装元素?

我尝试将相关的key应用于所有元素,但自keys are only sibling-unique起,这几乎没有影响。



class Item extends React.Component {
  constructor(props) {
    super(props);
    console.log("A new item was created");
  }
  componentDidMount() {
    console.log("I mounted");
  }
  componentWillUnmount() {
    console.log("I unmounted");
  }

  render() {
    return (
      <li>Item</li>
    );
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      itemList: 0
    };
  }

  componentDidMount() {
    setInterval(
      this.pickNewList.bind(this),
    2500);
  }

  pickNewList() {
    let newList;
    do {
      newList = Math.floor(Math.random() * 3);
    } while (newList === this.state.itemList);
    console.log(`Moving item from ${this.state.itemList} to ${newList}`);
    this.setState({
      itemList: newList
    });
  }

  render() {
    const uls = [...Array(3)].map((v, i) => {
      return (
        <ul key = {i}>
          <li>Non-item</li>
          {this.state.itemList === i ?
            <Item key="item" />
            : undefined} 
          <li>Non-item</li>
        </ul>
      );
    });
    return (
      <div>
        {uls}
      </div>
    );
  }
}

ReactDOM.render(( <
  App / >
), document.getElementById("app"));
&#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="app"></div>
&#13;
&#13;
&#13;

在我的特定用例中,我希望使用react-flip-move为移动设置动画,但由于每次都卸载/重新安装该元素,因此它不会被注册为移动。

0 个答案:

没有答案