Saya memiliki fungsi save() di aplikasi React saya yang menyimpan data dari rest api ke dalam array kosong saved[]. Tetapi masalahnya adalah, ketika saya menyegarkan halaman dan mengklik tombol Simpan, itu menimpa data dalam array, sepertinya saya tidak melihat di mana masalahnya? Kode saya sejauh ini adalah:

import React, { Component } from 'react';
import './news-hero.css';
import Carousel from "react-multi-carousel";
import "react-multi-carousel/lib/styles.css";

const responsive = {
    superLargeDesktop: {
        breakpoint: { max: 4000, min: 3000 },
        items: 1,
    },
    desktop: {
        breakpoint: { max: 3000, min: 1024 },
        items: 1,
    },
    tablet: {
        breakpoint: { max: 1024, min: 464 },
        items: 1,
    },
    mobile: {
        breakpoint: { max: 464, min: 0 },
        items: 1,
    },
};

class NewsHero extends Component {
    state = {
        loading: false,
        data: [],
        headline: [],
        saved: []
    }

    saved = headline => {
        this.setState(
         (prevState) => ({ saved: [...prevState.saved, headline] }),
          () => {
            console.log('Saved articles = ', this.state.saved);
            alert('Article saved');
            localStorage.setItem('saved', JSON.stringify(this.state.saved));
            localStorage.getItem('saved');
          });
      }

    constructor(props) {
        super(props)
        this.saved = this.saved.bind(this)
    }

    onError() {
        this.setState({
            imageUrl: "../assets/img-error.jpg"
        })
    }

    componentDidMount() {
        this.setState({ loading: true })
        fetch('https://newsapi.org/v2/everything?q=timbaland&domains=rollingstone.com,billboard.com&excludeDomains=townsquare.media&apiKey=7')
            .then(headline => headline.json())
            .then(headline => this.setState({ headline: headline.articles, loading: false }, () => console.log(headline.articles)))
    }

    render() {

        return (
            <div className="hero">
                <h2 className="text-left">News</h2>

                {this.state.loading
                    ? "loading..."
                    : <div>
                        <Carousel
                            additionalTransfrom={0}
                            showDots={true}
                            arrows={true}
                            autoPlaySpeed={3000}
                            autoPlay={false}
                            centerMode={false}
                            className="carousel-hero"
                            containerClass="container-with-dots"
                            dotListClass="dots"
                            draggable
                            focusOnSelect={false}
                            infinite
                            itemClass="carousel-top"
                            keyBoardControl
                            minimumTouchDrag={80}
                            renderButtonGroupOutside={false}
                            renderDotsOutside
                            responsive={responsive}>
                            {this.state.headline.map((post, indx) => {
                                return (
                                    <div className="text-left mt-5" key={indx}>
                                        <img className="media-img card-img-top card-img-hero" src={post.urlToImage} alt="Alt text"></img>
                                        <div className="card-body container hero-text-body">
                                            <h1 className="card-title hero-title text-truncate">{post.title}</h1>
                                            <button className="btn-primary btn mt-2 mb-4" onClick={() => this.saved(post)}>Add this article</button>
                                            <p className="card-text">{post.description}</p>
                                            <a href={post.url} target="_blank" rel="noopener noreferrer">Read More</a>
                                        </div>
                                    </div>
                                )
                            })}
                            {this.state.saved.map((post, indx) => {
                                return (
                                    <div className="text-left mt-5" key={indx}>
                                        <img className="media-img card-img-top card-img-hero" src={post.urlToImage} alt="Alt text"></img>
                                        <div className="card-body container hero-text-body">
                                            <h1 className="card-title hero-title text-truncate">{post.title}</h1>
                                            <button className="btn-primary btn mt-2 mb-4" onClick={() => this.saved(post)}>Add this article</button>
                                            <p className="card-text">{post.description}</p>
                                            <a href={post.url} target="_blank" rel="noopener noreferrer">Read More</a>
                                        </div>
                                    </div>
                                )
                            })}
                        </Carousel>

                    </div>
                }
            </div>
        )
    }
}
export default NewsHero;
1
Sole 22 Januari 2020, 02:22

2 jawaban

Jawaban Terbaik

Saya kira itu karena Anda tidak memulihkan larik saved dari Penyimpanan Lokal saat memasang komponen Anda.

Saat Anda menyegarkan halaman, komponen Anda kehilangan statusnya dan dipasang kembali.

Coba tambahkan:

    componentDidMount() {
        this.setState({ loading: true, saved: localStorage.getItem('saved') ? JSON.parse(localStorage.getItem('saved')) : [] })
        fetch('https://newsapi.org/v2/everything?q=timbaland&domains=rollingstone.com,billboard.com&excludeDomains=townsquare.media&apiKey=7')
            .then(headline => headline.json())
            .then(headline => this.setState({ headline: headline.articles, loading: false }, () => console.log(headline.articles)))
    }
1
Japsz 21 Januari 2020, 23:37

Anda perlu mendapatkan status dari penyimpanan lokal dan memperbaruinya, sebelum menulisnya ke penyimpanan lokal

constructor(props) {
    super(props)

    const saved = localStorage.getItem('saved');

    state = {
        loading: false,
        data: [],
        headline: [],
        saved: saved ? JSON.parse(saved) : []
    }

    this.saved = this.saved.bind(this)
}
3
Matt Huggins 21 Januari 2020, 23:48