将属性映射到react

将属性映射到react,第1张

将属性映射到react

据我了解,您要做的就是将组件的props转换为组件自己的状态。您总是可以

componentWillReceiveProps
像这样在组件的生命周期方法中将组件的props更改为组件的状态。

//componentclass MyComponent extends Component {  componentWillReceiveProps(newProps){     if(newProps.variableInProps != this.props.variableInProps){         this.setState({variableInState: newProps.variableInProps })     }  }  render() {    (<div onClick={this.props.executeAction.bind(this)}>      {this.state.variableInState}      </div>)  }  someOtherMethod() {    // I want to operate with state here, not with props    // that's why my div gets state from this.state instead of this.props    this.setState({variableInState: 'somevalue'})  }}export default connect((state, ownProperties) => {  return {    // So I want to change MyComponent.state.variableInState here    // but this method updates MyComponent props only    // What can I do?    variableInProps: state.myVariable  }}, {executeAction})(MyComponent);

componentWillReceiveProps
每当有新的道具进入组件时,方法总是由react执行,因此这是根据道具更新组件状态的正确位置。

更新:

The

componentWillReceiveProps
has been deprecated. So instead of this method
you can use
componentDidUpdate
method to do this.
componentDidUpdate

method takes previous props and previous state as arguments. So you can check
for the change in props and then set the state.


componentDidUpdate(prevProps) {  if(prevProps.variableInProps !== this.props.variableInProps){    this.setState({variableInState: this.props.variableInProps })  }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4900099.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存