为什么我的 React 组件渲染了两次? [英] Why is my React component is rendering twice?

查看:35
本文介绍了为什么我的 React 组件渲染了两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么我的 React 组件渲染了两次.所以我从 params 中提取一个电话号码并将其保存到 state 以便我可以在 Firestore 中进行搜索.除了渲染两次之外,一切似乎都运行良好......第一个渲染电话号码和零点.它第二次呈现所有数据时正确显示.有人可以指导我解决问题.

class 更新扩展组件 {构造函数(道具){超级(道具);const { 匹配 } = this.props;this.state = {电话号码:match.params.phoneNumber,点数:0,错误: ''}}getPoints = () =>{firebase.auth().onAuthStateChanged((user) => {如果(用户){const docRef = database.collection('users').doc(user.uid).collection('customers').doc(this.state.phoneNumber);docRef.get().then((doc) => {如果(文档存在){const 点 = doc.data().points;this.setState(() => ({点}));控制台日志(点);} 别的 {//在这种情况下 doc.data() 将是未定义的console.log("没有这样的文件!");const error = '此电话号码尚未注册...'this.setState(() => ({ error }));}}).catch(函数(错误){console.log("获取文档时出错:", error);});} 别的 {history.push('/')}});}componentDidMount() {如果(this.state.phoneNumber){this.getPoints();} 别的 {返回空;}}使成为() {返回 (<div><div><p>{this.state.phoneNumber} 有 {this.state.points} 分...</p><p>您想兑换还是添加积分?</p>

<div><button>兑换积分</button><button>添加点</button>

);}}导出默认更新;

解决方案

您正在以严格模式运行您的应用程序.转到 index.js 并注释严格模式标签.您会找到一个渲染.

发生这种情况是 React.StrictMode 的一个有意特性.它只发生在开发模式下,应该有助于在渲染阶段发现意外的副作用.

来自文档:

<块引用>

严格模式无法自动为您检测副作用,但它可以通过使它们更具确定性来帮助您发现它们.这是通过有意重复调用以下函数来完成的:...

^ 在本例中为 render 函数.

使用 React.StrictMode 时可能导致重新渲染的官方文档:

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

I don't know why my React component is rendering twice. So I am pulling a phone number from params and saving it to state so I can search through Firestore. Everything seems to be working fine except it renders twice... The first one renders the phone number and zero points. The second time it renders all the data is displayed correctly. Can someone 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;

解决方案

You are running your app in strict mode. Go to index.js and comment strict mode tag. You will find a single render.

This happens is an intentional feature of the React.StrictMode. It only happens in development mode and should help to find accidental side effects in the render phase.

From the docs:

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:...

^ In this case the render function.

Official documentation of what might cause re-rendering when using React.StrictMode:

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

这篇关于为什么我的 React 组件渲染了两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆