我不知道为什么我的 React 组件渲染了两次。因此,我从 params 中提取电话号码并将其保存到 state 中,以便我可以通过 Firestore 进行搜索。一切似乎都工作正常,除了渲染两次......第一次渲染电话号码和零点。第二次渲染时所有数据都正确显示。有人可以指导我解决方案吗?
class Update extends Component {
constructor(props) {
super(props);
const { match } = this.props;
this.state = {
phoneNumber: match.params.phoneNumber,
points: 0,
error: ''
}
}
getPoints = () => {
firebase.auth().onAuthStateChanged((user) => {
if(user) {
const docRef = database.collection('users').doc(user.uid).collection('customers').doc(this.state.phoneNumber);
docRef.get().then((doc) => {
if (doc.exists) {
const points = doc.data().points;
this.setState(() => ({ points }));
console.log(points);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
const error = 'This phone number is not registered yet...'
this.setState(() => ({ error }));
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
} else {
history.push('/')
}
});
}
componentDidMount() {
if(this.state.phoneNumber) {
this.getPoints();
} else {
return null;
}
}
render() {
return (
<div>
<div>
<p>{this.state.phoneNumber} has {this.state.points} points...</p>
<p>Would you like to redeem or add points?</p>
</div>
<div>
<button>Redeem Points</button>
<button>Add Points</button>
</div>
</div>
);
}
}
export default Update; Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您正在严格模式下运行您的应用程序。转到index.js并注释严格模式标记。您会发现一个渲染。
发生这种情况是 React.StrictMode 的一个有意的功能。它只发生在开发模式下,应该有助于发现渲染阶段的意外副作用。
来自文档:
^ 在本例中为
render函数。有关使用 React.StrictMode 时可能导致重新渲染的原因的官方文档:
https://reactjs.org/docs/strict- mode.html#检测意外副作用