我不知道为什么我的 React 组件会渲染两次。所以我从参数中提取一个电话号码并将其保存到状态,以便我可以搜索 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 的一个有意特性。它只发生在开发模式中,应该有助于发现渲染阶段的意外副作用。
来自文档:
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:...
^ 在本例中是 render
函数。
关于使用 React.StrictMode 时可能导致重新渲染的原因的官方文档:
https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects
关于javascript - 为什么我的 React 组件渲染了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48846289/