reactjs - 组件仅在第二次单击后才更新有效
问题描述
当我单击一个按钮时,我的代码在 firebase 数据库中添加了一个新项目,然后我希望页面中的对象列表自动更新,因为我不想手动重新加载页面。所以我想出了这段代码
constructor(props){
super(props);
this.state = {
groups: [],
code:'',
name:'',
update:true
}
}
async fetchGroups (id){
fetchGroupsFirebase(id).then((res) => {this.setState({groups:res})})
};
async componentDidUpdate(prevProps,prevState){
if(this.state.update !== prevState.update){
await this.fetchGroups(this.props.user.id);
}
}
handleCreateSubmit = async event => {
event.preventDefault();
const{name} = this.state;
try{
firestore.collection("groups").add({
title:name,
owner:this.props.user.id
})
.then((ref) => {
firestore.collection("user-group").add({
idGroup:ref.id,
idUser:this.props.user.id
});
});
this.setState({update: !this.state.update});
}catch(error){
console.error(error);
}
我在想什么,在我在 firebase 中添加新项目后,我更改了 state.update 变量,它触发了 componentDidUpdate,它调用了新的获取。
我尝试在提交函数中调用 fetchGroups 函数,但这也不起作用。
我做错了什么,我该如何解决?
解决方案
不会在初始渲染时调用 ComponentDidUpdate。您可以另外使用componentDidMount
或用功能组件替换类组件,并改用钩子useEffect
。
关于 useEffect,这可能是您的效果:
useEffect(() => {
await this.fetchGroups(this.props.user.id);
}, [update]);
由于您不能在类组件中使用 useEffect,因此您需要将其重写为函数式并将 this.state 替换为 useState。