React + Firebase - обновить состояние приращения кнопки Like / Clap до Firebase - PullRequest
0 голосов
/ 24 февраля 2020

Codesandbox: https://codesandbox.io/s/github/adamschwarcz/react-firebase-app

Я действительно новичок в реагировании и стрельбе, и я следовал этому учебнику , чтобы придумать это приложение (полное проект - ссылка на github здесь) - это «Добавить ваше приложение Wi sh»

Моя проблема в том, что я не могу сохранить количество хлопков для каждого поста в моей базе данных - этот компонент называется LikeButton. js.

Я пытался добавить некоторый аналогичный код Firebase (handleChange, handleSubmit, componentDidMount ... et c .. et c ..), как я узнал в руководстве для LikeButton. js для сохранения общего количества отсчетов в базе данных при каждом нажатии кнопки, а количество хлопков увеличивается на + 1.

Просто то, что я хочу - каждый раз, когда нажимается кнопка хлопка и начальный (' 0 ') состояние счета увеличивается до +1, текущий счет будет обновлен в базе данных.

Просто не могу найти решение, может кто-нибудь помочь?

Мой LikeButton. js код без всяких огней ase:

    import React, { Component } from 'react'
import firebase from '../../firebase.js';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

import './Like.css';

class LikeButton extends Component {


  state = {
    count: 0,
  }

  incrementLike = () => {
    let newCount = this.state.count + 1
    this.setState({
      count: newCount
    })

    console.log(this.state.count);
  } 

  render() {
    return(

      <div class="counter">

        <Button type="submit" color="primary" onChange={this.handleCount} onClick={this.incrementLike}>{this.state.count} ?</Button>

      </div>
    )
  }

}

export default LikeButton

My Add. js код с базой данных:

import React, { Component } from 'react';
import firebase from '../../firebase.js';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import FadeIn from "react-fade-in";
import Placeholder from '../Placeholder/Placeholder.js';
import LikeButton from '../Like/Like.js'
import './Add.css';


class Add extends Component {

    constructor() {
        super();
        this.state = {
          loading: true,
          currentItem: '',
          username: '',
          items: []
        }
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
      }

      handleChange(e) {
        this.setState({
          [e.target.name]: e.target.value
        });
      }

      handleSubmit(e) {
        e.preventDefault();
        const itemsRef = firebase.database().ref('items');
        const item = {
          title: this.state.currentItem,
          user: this.state.username
        }
        itemsRef.push(item);
        this.setState({
          currentItem: '',
          username: ''
        });
      }

      componentDidMount() {

        fetch("https://jsonplaceholder.typicode.com/posts")
        .then(response => response.json())
        .then(json => {
          setTimeout(() => this.setState({ loading: false }), 1500);
        });

        const itemsRef = firebase.database().ref('items');
        itemsRef.on('value', (snapshot) => {
          let items = snapshot.val();
          let newState = [];
          for (let item in items) {
            newState.push({
              id: item,
              title: items[item].title,
              user: items[item].user
            });
          }
          this.setState({
            items: newState
          });
        });
      }

      removeItem(itemId) {
        const itemRef = firebase.database().ref(`/items/${itemId}`);
        itemRef.remove();
      }


    render() {
      return (
        <div className="container">
        <div className="wrap">
            <section className="add-item">
                <h1>Napíš svoj wish</h1> 
                <h3>Možno prilepíš sebe, možno posunieš firmu.</h3>
                <form onSubmit={this.handleSubmit}>

                    <TextField 
                        id="filled-required" 
                        label="Meno" 
                        name="username" 
                        variant="filled"
                        value={this.state.username} 
                        onChange={this.handleChange}
                    />


                    <TextField
                        required
                        id="standard-multiline-flexible"
                        label="Tvoje prianie"
                        name="currentItem"
                        variant="filled"
                        multiline
                        rows="6"
                        rowsMax="8"
                        value={this.state.currentItem}
                        onChange={this.handleChange}
                    />

                    <Button 
                      type="submit"
                      variant="contained" 
                      color="primary">
                      Poslať wish
                    </Button>
                </form>

            </section>

            <section className='items-list'>
                <div className="item">
                    <div>
                        {this.state.items.map((item) => {
                            return (
                            <div>
                            {this.state.loading ? (
                              <>
                                <FadeIn>
                                <Placeholder />
                                </FadeIn>
                              </>
                            ) : (
                            <div className="wish" key={item.id}>
                                <FadeIn>
                                  <h2>{item.title}</h2>
                                  <div className="name">
                                      <p>poslal <span>{item.user}</span></p>
                                      <LikeButton />
                                  </div>
                                </FadeIn>
                            </div>
                            )}
                            </div>
                            )
                        })}
                    </div>
                </div>
            </section>
        </div>
        </div>
      );
    }
  }

export default Add

1 Ответ

0 голосов
/ 25 февраля 2020

Прежде всего, вы должны сообщить LikeComponent, что Wish будет обновляться, и вам также потребуется возможность доступа к clapCount из wi sh из LikeComponent. Это можно легко сделать, используя props. Вам следует переконфигурировать LikeComponent, чтобы принимать опору, аналогичную wish, которая будет отображать и изменять wi sh.

Итак, эта строка в Add.js <LikeButton /> вместо этого будет выглядеть как <LikeButton wish={item} />. Таким образом, ваш LikeComponent может получить доступ к item / wish.

Далее, в LikeComponent вам нужно удалить локальное состояние и вместо этого использовать количество хлопков, хранящееся в Firebase. К счастью, так как вы передаете wish через prop, вы можете просто реорганизовать LikeComponent, чтобы он выглядел следующим образом:

class LikeButton extends Component {
  incrementLike = () => {
    // TODO: Implement clap incrementation via Firebase updates
  } 

  render() {
    return(
      <div class="counter">
        <Button type="submit" color="primary" onClick={this.incrementLike}>{this.props.wish.clapCount} ?</Button>
      </div>
    )
  }
}

Далее нам нужно реализовать incrementLike. К счастью, поскольку мы получаем элемент wish, переданный нам через wish реквизит, мы можем легко обновить его следующим образом:

incrementLike = () => {
    // get a reference to the item we will be overwriting
    const wishRef = firebase.database().ref(`/items/${this.props.wish.id}`);

    // get the current value of the item in the database
    wishRef.once('value')
        .then(snapshot => {
            // get the value of the item. NOTE: this is unsafe if the item 
            // does not exist
            let updatedWish = snapshot.val();
            // update the item's desired property to the desired value
            updatedWish.clapCount = updatedWish.clapCount + 1;
            // replace the item with `wish.id` with the `updatedWish`
            wishRef.set(updatedWish);
        });
}

Хотя это должно работать только с несколькими настройками, я Я уверен, что есть лучший способ сделать это. Возможно, вы даже сможете избежать звонка на once('value'), поскольку вы передаете wish в качестве реквизита LikeComponent. Вы должны поиграть с этим.

Однако я настоятельно рекомендую вам изучить переход на Firebase Cloud Firestore. Это API более простой (на мой взгляд), чем база данных в реальном времени.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...