我想将我的“ componentDidMount”用作“ componentDidUpdate”。我希望能够填充
this.state.libelle_prerequis
喜欢
this.setState({libelle_prerequis:this.state.donnees.libelle_prerequis });
donnes = {id:1,libelle_prerequis:“ dde”}
constructor(props) {
super(props);
this.state = {
donnees: '',
libelle_prerequis: '',
error: '',
};
}
componentDidUpdate(prevsProp) {
if (prevsProp.store !== this.props.store) {
this.setState({
donnees: this.props.store.libellesprerequis.find((p) => p.id == this.props.libelleprerequis.match.params.id),
});
this.setState({ libelle_prerequis: this.state.donnees.libelle_prerequis });
}
}
componentDidMount() {
this.setState(() => ({
donnees: this.props.store.libellesprerequis.find((p) => p.id == this.props.libelleprerequis.match.params.id),
}));
}
render() {
<input
className="form-control"
type="text"
placeholder="Libellé"
autoFocus
value={this.state.libelle_prerequis ? this.state.donnees.libelle_prerequis : ''}
onChange={this.onLibellePrerequisChange}
/>;
}
答案 0 :(得分:2)
您可以执行以下操作:
getDonnees = () => {
const { store, libelleprerequis } = this.props;
return store.libellesprerequis.find((p) => p.id == libelleprerequis.match.params.id);
}
componentDidUpdate(prevsProp) {
if (prevsProp.store !== this.props.store) {
const donnees = this.getDonnees();
this.setState({
donnees,
libelle_prerequis: donness ? donnees.libelle_prerequis : ''
});
}
}
componentDidMount() {
const donnees = this.getDonnees()
this.setState({
donnees
});
}
您还可以添加检查以查看是否找到了donnees
。假设donness
是一个常量,其值将不会被更改。