Why does my React component render twice?
P粉268654873
P粉268654873 2023-10-16 12:47:00
0
1
691

I don't know why my React component is rendering twice. So I extract the phone number from params and save it into state so that I can search it via Firestore. Everything seems to be working fine except that it renders twice...the first time the phone number and the zero point are rendered. All data is displayed correctly on the second render. Can anyone guide me to the solution?

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;

P粉268654873
P粉268654873

reply all(1)
P粉608647033

You are running your application in strict mode. Go to index.js and comment out the strict mode tag. You will find a rendering.

This happening is an intentional feature of React.StrictMode. It only happens in development mode and should help detect unintended side effects during the rendering phase.

From the documentation:

^ In this case the render function.

Official documentation on what may cause re-rendering when using React.StrictMode:

https://reactjs.org/docs/strict-mode.html#Detecting unexpected side effects

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template