我不知道为什么我的 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;
您正在严格模式下运行您的应用程序。转到index.js并注释严格模式标记。您会发现单个渲染。
发生这种情况是 React.StrictMode 的一个有意的特性。它仅发生在开发模式中,并且应该有助于在渲染阶段发现意外的副作用。
来自文档:
严格模式无法自动为您检测副作用,但它可以通过使副作用更具确定性来帮助您发现它们。这是通过有意双重调用以下函数来完成的:...
^ 在这种情况下render
功能。
关于使用 React.StrictMode 时可能导致重新渲染的原因的官方文档:
https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)