在道具更改时设置React类状态



所以我的react类组件有这个问题。由于它处理";很多";当然,我不想使用功能组件,因为我认为这样更可读。在类组件的几层下面,我有一个特性组件,它将复选框中选定的特性分派到redux状态。

我的类组件需要知道这些更改,并根据存储在redux存储中的选定特性重新渲染。

问题是,它总是从mapStaeToProps函数中获得新的props,但我不能基于新的prop设置State(…(,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更改道具的唯一方法吗?

干杯

您不需要为每个道具更改设置状态。因为接收道具的组件将在其任何道具发生变化时自动重新渲染。

以为例

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

这里,只要组件A中的someProp发生更改,组件B就会自动重新渲染。

相关内容

  • 没有找到相关文章

最新更新