相关疑难解决方法(0)

为什么 useEffect 运行两次以及在 React 中如何处理好?

我有一个计数器和一个console.log()useEffect记录我状态中的每个变化,但是useEffect在挂载时被调用两次。我正在使用 React 18。这是我项目的CodeSandbox和以下代码:

import  { useState, useEffect } from "react";

const Counter = () => {
  const [count, setCount] = useState(5);

  useEffect(() => {
    console.log("rendered", count);
  }, [count]);

  return (
    <div>
      <h1> Counter </h1>
      <div> {count} </div>
      <button onClick={() => setCount(count + 1)}> click to increase </button>
    </div>
  );
};

export default Counter;
Run Code Online (Sandbox Code Playgroud)

javascript reactjs next.js

105
推荐指数
2
解决办法
7万
查看次数

为什么我的React组件渲染两次?

我不知道为什么我的React组件渲染两次.所以我从params中提取一个电话号码并将其保存到状态,以便我可以搜索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...' …
Run Code Online (Sandbox Code Playgroud)

javascript firebase reactjs google-cloud-firestore

7
推荐指数
5
解决办法
1万
查看次数