栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将属性映射到react

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将属性映射到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 })  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/369234.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号