gpt4 book ai didi

reactjs - 使用数据填充 React 表单(如果存在)

转载 作者:行者123 更新时间:2023-12-03 14:20:13 24 4
gpt4 key购买 nike

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

路径: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,
};

最佳答案

您可以稍微修改一下以下方法

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

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

}

这会将更新的 props 设置为 state。谢谢

关于reactjs - 使用数据填充 React 表单(如果存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44351644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com