為什麼我的 React 元件渲染了兩次?
P粉268654873
P粉268654873 2023-10-16 12:47:00
0
1
365

我不知道為什麼我的 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;

P粉268654873
P粉268654873

全部回覆(1)
P粉608647033

您正在嚴格模式下執行您的應用程式。轉到index.js並註釋嚴格模式標記。您會發現一個渲染。

發生這種情況是 React.StrictMode 的一個有意的功能。它只發生在開發模式下,應該有助於發現渲染階段的意外副作用。

來自文件:

^ 在本例中為 render 函數。

有關使用 React.StrictMode 時可能導致重新渲染的原因的官方文件:

https://reactjs.org/docs/strict- mode.html#偵測意外副作用

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!