如何在mount / unmount之间保持React组件状态? [英] How to keep React component state between mount/unmount?

查看:187
本文介绍了如何在mount / unmount之间保持React组件状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个维护内部状态的简单组件< StatefulView> 。我有另一个组件< App> 切换是否呈现< StatefulView>

I have a simple component <StatefulView> that maintains an internal state. I have another component <App> that toggles whether or not <StatefulView> is rendered.

但是,我希望在挂载/取消挂载之间保持< StatefulView> 的内部状态。

However, I want to keep <StatefulView>'s internal state between mounting/unmouting.

我想我可以在< App> 中实例化该组件,然后控制是否渲染/挂载。

I figured I could instantiate the component in <App> and then control whether its rendered/mounted.

var StatefulView = React.createClass({
  getInitialState: function() {
    return {
      count: 0
    }
  },
  inc: function() {
    this.setState({count: this.state.count+1})
  },
  render: function() {
    return (
        <div>
          <button onClick={this.inc}>inc</button>
          <div>count:{this.state.count}</div>
        </div>
    )
  }
});

var App = React.createClass({
  getInitialState: function() {
    return {
      show: true,
      component: <StatefulView/>
    }
  },
  toggle: function() {
    this.setState({show: !this.state.show})
  },
  render: function() {
    var content = this.state.show ? this.state.component : false
    return (
      <div>
        <button onClick={this.toggle}>toggle</button>
        {content}
      </div>
    )
  }
});

这显然不起作用,新的< StatefulView>

This apparently doesnt work and a new <StatefulView> is created on each toggle.

这是一个 JSFiddle

有没有办法在卸载后挂起到同一个组件,以便可以重新安装?

Is there a way to hang on to the same component after it is unmounted so it can be re-mounted?

推荐答案

我也在考虑这个问题。

我把我的尝试放在这个回购中: react-keep-state

I've put my attempts together in this repo: react-keep-state.

对我来说,最合适的解决方案如下:

For me, the most suitable solution was the following:

import React, { Component, PropTypes } from 'react';

// Set initial state
let state = { counter: 5 };

class Counter extends Component {

  constructor(props) {
    super(props);

    // Retrieve the last state
    this.state = state;

    this.onClick = this.onClick.bind(this);
  }

  componentWillUnmount() {
    // Remember state for the next mount
    state = this.state;
  }

  onClick(e) {
    e.preventDefault();
    this.setState(prev => ({ counter: prev.counter + 1 }));
  }

  render() {
    return (
      <div>
        <span>{ this.state.counter }</span>
        <button onClick={this.onClick}>Increase</button>
      </div>
    );
  }
}

export default Counter;

注意:如果此组件多次存在,则此方法不起作用在您的应用中。

Note: This approach does not work, if this component exists multiple times in your app.

请参阅回购以了解有关此问题的一些讨论(以及使用更高阶组件的另一种解决方案)。

Please see the repo for some discussion about this (and another solution that uses higher order components).

这篇关于如何在mount / unmount之间保持React组件状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆