当您要修改组件局部的(状态)变量,但要从props获取其初始值时,该怎么做?通过在componentDidMount中调用服务来设置道具的值。下面是简化的代码:
MyClass extends React.Component{
constructor(props){
super(props);
this.state = {
emailDetails: ''
}
}
componentDidMount(){
this.props.actions.getEmail();
}
render(){
return (
<div><input onChange={(event)=>{
//here i want to do something like so:
let newEmail = this.props.email.concat(event.target.value);
this.setState({emailDetails: newEmail});
}}
value={this.state.emailDetails}
/>
);
}
}
static mapStateToProps(state){
return {
email: state.userInfo.email
}
}
根据react文档,您不应该复制道具来说明,因为这是一种反模式。