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

标签 javascript reactjs firebase google-cloud-firestore

我不知道为什么我的 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/

相关文章:

javascript - 平滑 React 组件中的视差

javascript - 在输入字段中将 html 标签显示为 html

javascript - 如何与 javascript 传播运算符中的嵌套键合并?

javascript - 如何让代码在单击按钮后等待 X 秒再继续?

javascript - 在 React 中正确渲染 HTML 标签

node.js - 如何在react中显示来自node.js服务器的图像

javascript - 在 Electron/ express 应用程序中需要文件

javascript - React-Native Firebase 使用 FlatList 显示对象数组

java - 尝试将消息上传到 Firebase 数据库时出现错误 "found conflicting getters"

javascript - 哪个更好推广? IFRAME 或外部 Javascript