React Hooks useState更新数组

时间:2020-05-03 20:02:21

标签: javascript reactjs react-hooks

我希望从Google电子表格中获取数据,但是我对React钩子useState有疑问。

我有一个位置列表和Url列表。例如位置1:网址1和位置2:网址2。

首次渲染:

默认情况下,我会获得位置1和从网址1提取的数据。

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

点击位置5:

我从URL 1获得数据,但我希望从URL 5获得数据!

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

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

点击位置7:

我从网址5(预览状态!)获取数据。

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

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

点击位置44:

当我更改位置44时,现在可以从网址7获取数据

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

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

== Daily.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....');
    }
  }

1 个答案:

答案 0 :(得分:2)

根据我到目前为止的了解,您更有可能正在寻找类似这样的东西:

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(...)
}