繁体   English   中英

React Hooks useState 更新数组

[英]React Hooks useState updating an array

我希望从谷歌电子表格中获取数据,但我遇到了 React hooks useState 的问题。

我有一个位置列表和 Url 列表。 位置 1 的示例:url 1 和位置 2:url 2。

第一次渲染:

我得到默认位置 1 和从 url 1 获取的数据。

console.log(getTimes) & console.log(times)从 url 1 返回位置 1 的数据。

点击位置5:

我从 url 1 获取数据,但我想要来自 Url 5 的数据!

console.log(getTimes)从 Url 5 返回数据

console.log(times)从 Url 1 返回数据

点击位置7:

我从 Url 5 获取数据(预览 state。)。

console.log(getTimes)从 Url 7 返回数据

console.log(times)从 Url 5 返回数据

点击位置 44:

当我更改位置 44 时,我现在从 url 7 获取数据

console.log(getTimes)从 Url 44 返回数据

console.log(times)从 Url 7 返回数据

==每日.js==

function Daily({ locationProps = 1, root }) {
      const context = useContext(ThemeContext);
      const localization = useCallback(() => {
        if (root && cookies.get("location") !== undefined) {
          return cookies.get("location");
        }
        return locationProps;
      }, [locationProps, root]);

    const _data = useRef(new Data());

    useEffect(() => {
      _data.current.getTimesFromGoogleSheets();
      }, [locationProps]);


    const getTimes =()=>  _data.current.getTimes();

    const times = useState(()=>getTimes());  <------- here is the problem useState dont update



**==data.js==**

class Data {
  constructor(locationProps) {
    this.locationProps=locationProps
    this.updateData();
  }

  getTimes(date = null) {
    date = date === null ? moment().format('DD/MM/YYYY') : date;
    var data = this.getData();
    return data ? data[date] : [];
  }

  getSpeadsheetUrl() {
    return config.Data[this.locationProps];
  }



  getTimesFromGoogleSheets() {
    var spreadsheetUrl = this.getSpeadsheetUrl();

    if (!spreadsheetUrl) {
      alert('CSV not set');
    }

    return csvtojson()
      .fromStream(request.get(`${spreadsheetUrl}&_cacheBust=${Math.random()}`))
      .then(json => {
        this.storeData(json);
      });
  }

  storeData(Data = []) {
    var formatted_data = {};
    Data.forEach(day => {
      formatted_data[day.Date] = day;
    });
    window.localStorage.setItem('Data', JSON.stringify(formatted_data));
    window.localStorage.setItem('Data_lastUpdated', moment().unix());
  }

  getData() {
    var _Data = window.localStorage.getItem('Data');
    return _Data ? JSON.parse(_Data) : null;
  }

  getLastUpdatedTime() {
    return window.localStorage.getItem('Data_lastUpdated');
  }

  updateData() {
    var lastUpdatedDiff = moment().unix() - parseInt(this.getLastUpdatedTime());
    var alreadyHasData = this.getData() ? true : false;
    if (
      lastUpdatedDiff > config.Data.refreshRate * 60 ||
      !alreadyHasData
    ) {
      this.getTimesFromGoogleSheets().then(() => {
        if (!alreadyHasData) {
          setTimeout(function() {
            window.location.reload();
          }, 2000);
        }
      });
      console.info('Updating Data....');
    }
  }

根据我目前所知道的,你更有可能寻找这样的东西:

function Daily({ locationProps = 1, root }) {
    const context = useContext(ThemeContext);
    const localization = useCallback(() => {
        if (root && cookies.get("location") !== undefined) {
            return cookies.get("location");
        }
        return locationProps;
    }, [locationProps, root]);

    const _data = useRef(new Data());

    // Use times to display, use setTimes to change the data, maybe as part of your effect?
    const [times, setTimes] = useState(_data.current.getTimes());

    useEffect(() => {
        _data.current.getTimesFromGoogleSheets();
        const newTimes = _data.current.getTimes();
        setTimes(newTimes);
    }, [locationProps]);

    // times.map(...)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM