【问题标题】:Easy way to set default state values in React JS component在 React JS 组件中设置默认状态值的简单方法
【发布时间】:2019-11-29 12:13:31
【问题描述】:

有没有简单的方法可以将组件的状态转换为默认状态。

通常我通过设置如下默认值来为此创建一个函数。有没有其他方法可以代替这个?

import React, { Component } from 'react';

class Person extends Component {
    state = {
        firstName: null,
        lastName : null,
        age      : null,
        address  : null,
    }

    // Set state to default state
    setDefaultState = () => {
        this.setState({
            firstName: null,
            lastName : null,
            age      : null,
            address  : null,
        });
    }

    render() {
        return(
            <div>
                Person Component
            </div>
        );
    }
}

export default Person;

react js 中有没有为此预定义的函数。

提前致谢。 :)

【问题讨论】:

  • 这就是你要找的东西吗。stackoverflow.com/questions/21749798/…
  • 在那个答案中,说的是,没有为此的预定义函数。我需要的是,当我创建一个模式时,我需要在隐藏时将其状态设置为默认状态。为此,我目前正在使用我的问题setDefaultState() 中的上述功能。我要问的是,react js 中是否有任何 预定义函数 而不是我目前的方法。
  • 是的,很抱歉误导您所做的事情与包括我在内的其他人一样。编码愉快!
  • 好的,谢谢@ThakurKarthik

标签: reactjs react-state


【解决方案1】:

这是一种方法

initialState = {
    firstName: null,
    lastName : null,
    age      : null,
    address  : null,
}

class Person extends Component {
    state = {
        ...initialState
    }

    // Set state to default state
    setDefaultState = () => {
        this.setState({
            ...initialState
        });
    }

【讨论】:

  • 是的。但是是否有任何预定义的函数来执行此操作,而不是创建一个新函数来将当前状态转换为 react js 中的默认状态?
猜你喜欢
  • 2018-12-30
  • 2021-04-17
  • 2021-04-25
  • 2020-03-17
  • 1970-01-01
  • 2016-08-12
  • 1970-01-01
  • 2018-06-30
  • 2018-12-10
相关资源
最近更新 更多