反应状态存储和输出重复值

时间:2019-01-15 20:58:58

标签: javascript reactjs firebase state

我认为这是一个相对容易解决的小问题,但我无法完全解决。我对React很新。我决定制作一个小示例应用程序,该应用程序仅接收来自两个字段的输入,然后将它们保存到Firebase并在页面上输出这些值。就提交数据和检索数据而言,它工作得很好,但是当我单击“提交”按钮将数据添加到Firebase时,它似乎复制了状态中存储的数据并渲染了两次:

父组件:

$timer = new-object timers.timer 

$action = {write-host "Timer Elapse Event: $(get-date -Format ‘HH:mm:ss’)"} 
$timer.Interval = 3000 #3 seconds  

Register-ObjectEvent -InputObject $timer -EventName elapsed –SourceIdentifier  thetimer -Action $action 

$timer.start()

#to stop run 
$timer.stop() 
#cleanup 
Unregister-Event thetimer

子组件(表单字段)

import React, { Component, Fragment } from 'react';

import firebase from '../../config/firebase';
import QuestFormField from './QuestFormField/QuestFormField';
import QuestFormSelection from './QuestFormSelection/QuestFormSelection';

import classes from './QuestForm.css';

class QuestForm extends Component {
    state = {
        value: '',
        points: 0,
        items: []
    }

    questHandler = e => {
        this.setState({
            value: e.target.value,
        });
    }

    pointsHandler = e => {
        this.setState({
            points: e.target.value,
        });
    }

    submitHandler = e => {
        e.preventDefault();
        const itemsRef = firebase.database().ref('quest');
        const items = {
            quest: this.state.value,
            points: this.state.points
        }
        itemsRef.push(items);
        this.setState({
            value: '',
            points: 0
        });
    }

    render () {
        return (
            <Fragment>
                <form className={classes.Form} onSubmit={this.submitHandler}>
                    <QuestFormField val='Quest' inputType='text' name='quest' value={this.state.value} changed={this.questHandler} />
                    <QuestFormField val='Points' inputType='number' name='points' value={this.state.points} changed={this.pointsHandler} />
                    <button>Away! To Firebase!</button>
                </form>
                <QuestFormSelection />
            </Fragment>
        );
    }

}

export default QuestForm;

子组件B(数据检索器/显示器)

import React from 'react';

import classes from './QuestFormField.css';

const QuestFormField = (props) => (
    <div className={classes.Container}>
        <label htmlFor={props.name}>{props.val}</label>
        <input type={props.inputType} name={props.name} onChange={props.changed}/>
    </div>
);

export default QuestFormField;

此处的行为示例:

https://i.gyazo.com/c70972f8b260838b1673d360d1bec9cc.mp4

任何指针都可以帮助:)

1 个答案:

答案 0 :(得分:2)

我自己还没有使用过Firebase,但是看起来下面的代码正在设置一个侦听器来查询“请求”更改,该更改将在每次更改发生时执行,但是您在数据库更改之外定义了const quests = []处理程序。这意味着在第二次更改时,您会将快照中的所有内容推入可能已经添加了先前快照的同一quests阵列中。我相信您可以通过在侦听器函数内移动quests变量来解决此问题,如下所示。

componentDidMount() {
    const database = firebase.database();

    database.ref('quest').on('value', (snapshot) => {
        const quests = [];
        snapshot.forEach((childSnapshot) => {
            quests.push({
                id: childSnapshot.key,
                quest: childSnapshot.val().quest,
                points: childSnapshot.val().points,
            });
        });
        console.log(quests);
        this.setState(() => {
            return {
                quests: quests
            }
        });
        console.log(this.state.quests);
    });
}