将React类建立在Prop Change上

发布于 2025-01-17 08:15:23 字数 2689 浏览 0 评论 0原文

所以我的反应类组件遇到了这个问题。 由于它处理“很多”状态,我不想使用功能组件,因为我认为它更具可读性。 在我的类组件下面几层,我有一个功能组件,它将选定的功能从复选框分派到 redux 状态。

我的类组件需要了解这些更改,并根据存储在 redux 存储中的所选功能重新渲染。

问题是,它总是从 mapStaeToProps 函数获取新的道具,但我无法基于新的道具 setState(...) , bc componentDidMount 在开始时只运行一次,或者 componentWillReceiveProps() 不再存在。

import { connect } from 'react-redux';

import TaggingComponent from '../../../content-components/TaggingComponent';
import SupplyAmount from '../../../content-components/SupplyAmount';
import FeaturesComponent from '../../../content-components/FeaturesComponent';
import './TokenGenerator.css';

const features = {
  Features: [
    'Mintable',
    'Burnable',
    'Pausable',
    'Permit',
    'Votes',
    'Flash Minting',
    'Snapchots'
  ],
  'Access Control': ['Ownable', 'Roles'],
  Upgradeability: ['Transparent', 'UUPS']
};

class TokenGenerator extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tokenName: '',
      shortName: '',
      supplyAmount: null,
      selectedFeatures: this.props.selectedFeatures
    };
  }

  static getDerivedStateFromProps(props, current_state) {
    if (current_state.selectedFeatures !== props.selectedFeatures) {
      return {
        selectedFeatures: props.selectedFeatures
      };
    }
    return null;
  }

  setTokenName = (e) => {
    this.setState({ tokenName: e.target.value });
  };

  setShortageName = (e) => {
    this.setState({ shortName: e.target.value });
  };

  setAmount = (e) => {
    this.setState({ supplyAmount: e.target.value });
  };

  render() {
    return (
      <div className="grid grid-cols-7 gap-10">
        {/* Name and shortage input */}
        <TaggingComponent
          setTokenName={this.setTokenName}
          setShortageName={this.setShortageName}
        />
        {/* Token supply */}
        <SupplyAmount setAmount={this.setAmount} />
        {/* Tokenfeatures */}

        <FeaturesComponent features={features} />

        {/* Selected Features listing */}
        <div className="card-bg border-2 border-white text-white p-11 rounded col-span-5 row-span-5">
          <h4 className="text-center">Selected Features</h4>
          {this.state.selectedFeatures.map((feature) => {
            return <p key={feature}>{feature}</p>;
          })}
        </div>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  console.log(state);
  return { selectedFeatures: state.tokenGeneratorState.selectedFeatures };
};

export default connect(mapStateToProps)(TokenGenerator);

新的 getDerivedStateFromProps 方法是更新状态 vom 更改 props 的唯一方法吗?

干杯

So I´m having this issue with my react class component.
Since it´s handling "a lot" of state, I don´t want to use a functional component bc I think it is more readable like so.
A few layers down from my class component I have a features component, which dispatches selected features from checkboxes to the redux state.

My class component needs to know these changes and re-renders based on the selected features, stored in the redux store.

The problem is, it always gets the new props from the mapStaeToProps function, but I can´t setState(...) based on the new props, bc componentDidMount only runs once at the beginning or componentWillReceiveProps() doesn´t exist anymore.

import { connect } from 'react-redux';

import TaggingComponent from '../../../content-components/TaggingComponent';
import SupplyAmount from '../../../content-components/SupplyAmount';
import FeaturesComponent from '../../../content-components/FeaturesComponent';
import './TokenGenerator.css';

const features = {
  Features: [
    'Mintable',
    'Burnable',
    'Pausable',
    'Permit',
    'Votes',
    'Flash Minting',
    'Snapchots'
  ],
  'Access Control': ['Ownable', 'Roles'],
  Upgradeability: ['Transparent', 'UUPS']
};

class TokenGenerator extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tokenName: '',
      shortName: '',
      supplyAmount: null,
      selectedFeatures: this.props.selectedFeatures
    };
  }

  static getDerivedStateFromProps(props, current_state) {
    if (current_state.selectedFeatures !== props.selectedFeatures) {
      return {
        selectedFeatures: props.selectedFeatures
      };
    }
    return null;
  }

  setTokenName = (e) => {
    this.setState({ tokenName: e.target.value });
  };

  setShortageName = (e) => {
    this.setState({ shortName: e.target.value });
  };

  setAmount = (e) => {
    this.setState({ supplyAmount: e.target.value });
  };

  render() {
    return (
      <div className="grid grid-cols-7 gap-10">
        {/* Name and shortage input */}
        <TaggingComponent
          setTokenName={this.setTokenName}
          setShortageName={this.setShortageName}
        />
        {/* Token supply */}
        <SupplyAmount setAmount={this.setAmount} />
        {/* Tokenfeatures */}

        <FeaturesComponent features={features} />

        {/* Selected Features listing */}
        <div className="card-bg border-2 border-white text-white p-11 rounded col-span-5 row-span-5">
          <h4 className="text-center">Selected Features</h4>
          {this.state.selectedFeatures.map((feature) => {
            return <p key={feature}>{feature}</p>;
          })}
        </div>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  console.log(state);
  return { selectedFeatures: state.tokenGeneratorState.selectedFeatures };
};

export default connect(mapStateToProps)(TokenGenerator);

Is the new getDerivedStateFromProps method the only way to update state vom changing props?

Cheers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

世界如花海般美丽 2025-01-24 08:15:23

您不需要为每个道具更改设置状态。因为只要任何一个 props 发生变化,接收 props 的组件就会自动重新渲染。

以此为例,

class ComponentA {
    render() {
        <ComponentB someProp={someDynamicallyChangingValue} />
    }
}

class ComponentB {
    render() {
        <div>{this.props.someProp}</div>
    }
}

只要 ComponentA 中的 someProp 发生变化,ComponentB 就会自动重新渲染。

You don't need to set state for each prop change. Because the component which receives props will re-render automatically whenever any of it's props changes.

Take this as example,

class ComponentA {
    render() {
        <ComponentB someProp={someDynamicallyChangingValue} />
    }
}

class ComponentB {
    render() {
        <div>{this.props.someProp}</div>
    }
}

Here, the ComponentB will be automatically re-rendered whenever someProp is changed in ComponentA.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文