我尝试使代码干净。我有两个选择。
第一
state = {
onChange: this.props.onChange,
}
第二
state = {
onChange: null,
}
componentDidMount(){
this.setState({
onChange: this.props.onChange,
});
}
我想在代码中使用1st,因为它看起来更整洁。 但我不确定是第2种作品吗?请告知。
答案 0 :(得分:1)
理想情况下,应避免使用props值初始化状态,这是一种反模式。进一步了解here
此外,如果props对象中已经存在一些值,则应尽可能尝试直接在组件中使用该值,并避免在Parent和Child组件中重复相同的值。
但是如果出于某种原因,您的子组件中也必须具有相同的数据,那么在这种情况下,请参考下面的代码片段。
public class StaffProfilesModel
{
public string ProfileId { get; set; }
public bool EmployeeActive { get; set; }
public bool Artist { get; set; }
public bool Operations { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Title { get; set; }
public string ProfilePictureId { get; set; }
public string SampleOneId { get; set; }
public string SampleTwoId { get; set; }
public string SampleThreeId { get; set; }
}
如果this.props.onChange存在,则将更新本地状态值,否则将设置为null。希望这能给您一些看法,让我知道您是否仍然感到困惑。