Javascript 在 React + ES6 中重置初始状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45200535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:57:28  来源:igfitidea点击:

Reset initial state in React + ES6

javascriptreactjsecmascript-6

提问by Zack Shapiro

I have a class, ElementBuilderbelow, and when the user saves the Elementthey've built, I want the state to reset to the values below.

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

I have some functions in this class that I haven't provided but that change the state of title, size, and color.

我在这个班的状态的一些功能,我还没有提供,但这种变化titlesizecolor

In ES 5, I would have a getInitialStatefunction on my class and could call this.getInitialState()in a function.

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

This element lives in my app for the lifecycle of a logged in user and I want the default values to always be the same regardless of past usage.

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

How do I achieve this without writing a function that sets an object of default values (or maybe that's the answer)? thanks!

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

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

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

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

回答by quotesBro

You may use a getter function:

您可以使用 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);
  }
}

or just a variable:

或者只是一个变量:

constructor(props) {
  super(props);

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

回答by wolverine ks

Using the proposed class fields, you could do something like this:

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

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)
    }
}

回答by Felix Kling

Since the initial state doesn't seem to depend on anything instance specific, just define the value outside the class:

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

const initialState = {...};

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

        this.state = initialState;
    }

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

回答by Charles Romney

Use an High Order Component to clear component state (rerender)

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

Exemple Element.jsx :

示例 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