时间:2018-04-25 19:35:54

标签: reactjs

我(非常)是React的新手,我正在构建一个小网页作为我学习过程的一部分。我的网页是一个货币表(使用API​​给出),我应该能够删除和添加货币并恢复到表格的原始状态。

删除任意多个,然后第一次恢复正常工作。当我删除然后再次恢复时 - 没有任何反应。

我的应用程序状态有一个显示的数据'属性,保存表格中当前显示的数据,以及“初始数据”。属性,保存我在点击“还原”时应该出现的原始数据。

从我的调试过程中,似乎点击了'还原'按钮关系" initialData'显示数据',以便在第二次恢复时没有任何反应。

这是我的主要App组件的代码:

import React, { Component } from 'react';
import CurrencyTable from './currencyTable';
import SearchBar from './searchBar';
// import _ from 'lodash';
import RevertButton from './revertButton';
import logo from './logo.svg';
import './App.css';
import './bootstrap.min.css';

const API_KEY = '7312269b011ac267b5d9663c4a479c24';
const endpoint = 'latest';

class App extends Component {

    constructor(props){
        super(props);

        this.state={
            shownCountries: [],
            initialCountries: [],
            allData: [],
            shownData:[],
            initialData:[],
            value:'',
        }
    }

    componentDidMount(){
        this.setState({shownCountries: ['EUR', 'ILS', 'USD', 'GBP', 'AUD']});
        this.setState({initialCountries: ['EUR', 'ILS', 'USD', 'GBP', 'AUD']});

        // localStorage.setItem('shownC', JSON.stringify(this.shownCountries));
        const cachedCountries = localStorage.getItem('shownC');
        if (!cachedCountries)
            localStorage.setItem('shownC', JSON.stringify(this.state.shownCountries));
        else
            this.setState({shownCountries: JSON.parse(cachedCountries)});

        fetch(`http://data.fixer.io/api/${endpoint}?access_key=${API_KEY}`)
            .then(results => {
                return results.json();
            })
            .then(result => {
                let rates = result.rates;
                let shownData = [];
                let initialData = [];
                let allData = [];
                let i = 0;
                let j = 0;
                let k = 0;

                //check for saved data in local storage:
                Object.keys(rates).forEach(key => {
                    if (this.state.shownCountries.indexOf(key) > -1){
                        shownData[j] = {rate: key, value: rates[key], button: "btn btn-danger red"};
                        j++;
                    }
                    if (this.state.initialCountries.indexOf(key) > -1){
                        initialData[k] = {rate: key, value: rates[key], button: "btn btn-danger red"};
                        k++;
                    }
                    allData[i] = {rate: key, value: rates[key], button: "btn btn-danger red"};
                    i++;
                })

                this.setState({allData: allData, initialData: initialData, shownData: shownData});
            })
    }

    findValue(rate){
        for (let i=0; i<this.state.allData.length; i++){
            if (this.state.allData[i].rate === rate)
                return this.state.allData[i].value;
        }
    }

    handleChangeValue = value => {
        let newRateObj = {rate: value, value: this.findValue(value), button: "btn btn-danger red"};
        this.setState({
            shownData: this.state.shownData.concat([newRateObj])
        });
        this.state.shownCountries.concat([value]);
        localStorage.setItem('shownC', JSON.stringify(this.state.shownCountries));
    }

    handleRevertClick = () => {
        console.log(this.state.initialData);
        localStorage.setItem('shownC', JSON.stringify(this.state.initialCountries));
        this.setState({shownData: this.state.initialData});
        console.log(this.state.initialData);
    };

    saveToLocalStorage(data) {
        localStorage.setItem('shownC', JSON.stringify(this.getShownCList(data)));
    }

    getShownCList(data){
        let shownC = [];
        for (let i=0;i<data.length;i++){
            shownC.push(data[i].rate);
        }
        // console.log(shownC);
        return shownC;
    }


    render() {
        console.log("initialData is:");
        console.log(this.state.initialData);
        if (this.state.initialData.length===0)
            return 'loading...';
        return (
            <div className="headDiv">
                <div className="App">
                    <header className="App-header">
                        <img src={logo} className="App-logo" alt="logo" />
                        <h1 className="App-title">Niki's React Currency App</h1>
                    </header>
                </div>
                <div className="mainDiv">
                    <div className="col">
                        <div className="col-lg-6 currencyTableContainer">
                            <CurrencyTable
                                data = { this.state.shownData }
                                saveToLS= {(data) => {
                                    this.saveToLocalStorage(data)}}/>
                        </div>
                        <div className="col-lg-6 searchAndRevertContainer">
                            <div className="row">
                                <div className="row-md-4">
                                    <SearchBar
                                        value={this.state.value}
                                        allData = { this.state.allData }
                                        onChangeValue={this.handleChangeValue}/>
                                </div>
                                <div className="row-md-4 revertButton">
                                    <RevertButton
                                        onClick={this.handleRevertClick}/>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

        );
    }
}

export default App;

这里是表组件中onClick函数的代码,它删除了一行(之后initialData似乎出错了):

onRemoveClick(rate){
    const newShownData = this.state.myTableData;
    let index = _.findIndex(newShownData, {rate: rate});
    if (index>-1)
        newShownData.splice(index, 1);
    this.setState({myTableData: newShownData});
    this.props.saveToLS(this.state.myTableData);
}

我超级失落,有帮助吗? :)

1 个答案:

答案 0 :(得分:0)

通过在将其值赋给shownData:

之前创建initialData的深层副本来解决
...
var temp = JSON.parse(JSON.stringify(this.initialData))
this.setState({shownData: temp});
...