【问题标题】:Reset initial state in React + ES6在 React + ES6 中重置初始状态
【发布时间】:2017-07-19 20:36:05
【问题描述】:

我有一个类,ElementBuilder 下面,当用户保存他们构建的Element 时,我希望将状态重置为下面的值。

我在这个类中有一些我没有提供但会改变titlesizecolor 状态的函数。

在 ES 5 中,我的类中有一个 getInitialState 函数,并且可以在函数中调用 this.getInitialState()

这个元素存在于我的应用程序中,用于登录用户的生命周期,我希望默认值始终保持不变,无论过去的使用情况如何。

如何在不编写设置默认值对象的函数的情况下实现这一点(或者也许这就是答案)?谢谢!

class ElementBuilder extends Component {
    constructor(props) {
        super(props);

        this.state = {
            title: 'Testing,
            size: 100,
            color: '#4d96ce',
        };
    }

    resetBuilder() {
        this.setState({ this.getInitialState() });
    }
}

【问题讨论】:

  • 你总是可以用初始值在类之外定义一个常量。然后使用它来初始化状态并在任何给定时间重置。
  • 对于健壮的状态管理,请查看redux with redux,您可以轻松地执行各种操作,例如撤消、重做和时间旅行

标签: javascript reactjs ecmascript-6


【解决方案1】:

你可以使用getter函数:

class ElementBuilder extends Component {
  constructor(props) {
    super(props);

    this.state = this.initialState;
  }

  get initialState() {
    return {
      title: 'Testing',
      size: 100,
      color: '#4d96ce',
    };
  }

  resetBuilder() {
    this.setState(this.initialState);
  }
}

或者只是一个变量:

constructor(props) {
  super(props);

  this.initialState = {
    title: 'Testing',
    size: 100,
    color: '#4d96ce',
  };
  this.state = this.initialState;
}

【讨论】:

  • getter 函数仍然是一个函数 ;)
  • @FelixKling 哦,我错过了“不写函数” :) 但是第二个选项看起来不错。
  • 这很好。谢谢米哈伊尔和菲利克斯!
  • 请注意,我认为在构造函数中你应该调用 this.getInitialState 而不是 this.initialState 并且在 getInitialState 函数中你应该使用 this.setState 而不是 this.state。
  • resetBuilder中的代码应该是this.setState(this.initialState);吗?
【解决方案2】:

使用建议的类字段,您可以执行以下操作:

class ElementBuilder extends Component {
    static initialState = {
        title: 'Testing',
        size: 100,
        color: '#4d96ce'
    }
    
    constructor(props) {
        super(props)

        this.state = ElementBuilder.initialState
    }

    resetBuilder() {
        this.setState(ElementBuilder.initialState)
    }
}

【讨论】:

    【解决方案3】:

    由于初始状态似乎不依赖于任何特定的实例,只需在类之外定义值:

    const initialState = {...};
    
    class ElementBuilder extends Component {
        constructor(props) {
            super(props);
    
            this.state = initialState;
        }
    
        resetBuilder() {
            this.setState(initialState);
        }
    }
    

    【讨论】:

    • 为什么我们将initialState设置为class而不是变量?
    • @FelixKling :this.setState(intialState) 背后的原因是什么,而不是使用这种语法 this.setState({intialState}) 。你能解释一下吗?
    • @SakthiSureshAnand: this.setState({intialState})this.setState({intialState: initalState}) 相同,即状态最终将只有一个条目,initialState。这不是我们想要的。 initialState 的每个属性都应该是状态的一部分。出于同样的原因,我们使用this.state = initialState; 而不是this.state = {initialState};
    • 初始化状态后,当我更新状态时,它也会更新 const 对象。
    • @Jay:然后创建一个副本。根据结构,浅拷贝可能就足够了。 this.state = {...initialState};.
    【解决方案4】:

    使用高阶组件清除组件状态(重新渲染)

    示例 Element.jsx :

    // Target ----- //
    
    class Element extends Component {
    
      constructor(props){
        super(props)
        const {
            initState = {}
        } = props
        this.state = {initState}
      }
    
      render() {
        return (
            <div className="element-x">
                {...}
            </div>
        )
      }
    }
    
    // Target Manager ----- //
    
    class ElementMgr extends Component {
    
        constructor(props){
            super(props)
            const {
                hash = 0
            } = props
            this.state = {
                hash, // hash is a post.id 
                load: false
            }
        }
    
        render() {
            const {load} = this.state
            if (load) {
                return (<div className="element-x"/>)
            } else {
                return (<Element {...this.props}/>)
            }
        }
    
        componentWillReceiveProps(nextProps) {
            const {hash = 0} = nextProps
            if (hash !== this.state.hash) {
                this.setState({load:true})
                setTimeout(() => this.setState({
                    hash,
                    load:false
                }),0)
            }
        }
    }
    
    export default ElementMgr
    

    【讨论】:

      猜你喜欢
      • 2018-03-24
      • 2019-07-20
      • 2020-11-02
      • 2021-04-13
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      相关资源
      最近更新 更多