2017-06-04 90 views
2

我正尝试使用我的mongoDB中的数据预填充表单。我认为我应该使用componentDidUpdate()来设置表单字段的状态,但是,页面会进入无限循环。非常新的反应,所以这可能是一个明显的问题,我只是无法找到解决方案。使用数据填充反应表单(如果存在的话)

路径:ContactDetailsComponent.js

export default class ContactDetails extends React.Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     'name.first': '', 
    }; 

    this.handleInputChange = this.handleInputChange.bind(this); 
    this.handleSubmit = this.handleSubmit.bind(this); 
    } 

    componentWillReceiveProps(nextProps) { 
    var profileCandidate = this.props.profileCandidate; 
    var firstName = profileCandidate && profileCandidate.name && profileCandidate.name.first; 

    this.setState({ 
     'name.first': firstName, 
    }) 

    } 

    handleInputChange(event) { 
    const target = event.target; 
    const value = target.type === 'checkbox' ? target.checked : target.value; 
    const name = target.name; 

    this.setState({ 
     [name]: value 
    }); 
    } 

    render() { 
    return (
     <div> 
     <form onSubmit={this.handleSubmit} noValidate> 

      <input 
      name="name.first" 
      type="text" 
      value={this.state['name.first']} 
      onChange={this.handleInputChange} 
      className={this.state.errors['name.first'] ? "validate invalid" : "validate" } 
      /> 

     </form> 
     </div> 

    ) 
    } 
} 

ContactDetails.propTypes = { 
    profileCandidate: PropTypes.object, 
}; 
+0

你应该使用'nextProps',因为它们是道具的新值​​。你正在使用'this.props'这是道具的旧价值。 – nrgwsth

回答

1

,可以稍微修改你下面的方法

componentWillReceiveProps(nextProps) { 
    var profileCandidate = nextProps.profileCandidate; 
    var firstName = profileCandidate && profileCandidate.name && profileCandidate.name.first; 

    this.setState({ 
    'name.first': firstName, 
    }) 

} 

这将设置更新的道具状态。 谢谢