如何将状态值插入函数?

时间:2017-09-14 22:57:41

标签: reactjs

我有一个从firebase数据库查询生成的数组。

我希望将其保存在状态中,以便随着数据的变化,它将重新渲染屏幕。

我似乎无法从状态获取值到我的函数中。如果我从数组中放入值,它就可以工作,但是当数据发生变化时它不会自动重新渲染。

使用数组的屏幕截图...注意控制台日志正在打印状态设置正确。 enter image description here

这里是错误的 enter image description here

它必须在第101行附近,但我无法找到正确的语法来使其工作。

更新:我没有初始化状态,这是错误的一部分。

import React, { Component } from 'react';
import Flexbox from 'flexbox-react';

import firebaseApp from '../api/firebase';
import GeoFire from 'geofire';

var geoRef = firebaseApp.database().ref('shiftgeo');
var geoFire = new GeoFire(geoRef);
var ref = geoFire.ref();  // ref === firebaseRef
var shiftKeys = []; // this array will hold the keys from the geoFire results
var shifts = []; // this array will hold the actual shift data of shifts in the geo, then we will filter it later

console.log(firebaseApp);

export class App extends React.Component {
  constructor() {
    super();
    this.state = {
      fname: 'Chris',
      lname: 'Chong',
      cellphone: '503 830 4313',
      email: 'chris@ehotleads.com',
      dataSource: ''
    };
  }
  componentWillMount() {
    let email = 'chris@ehotleads.com';
    let password = '123456789';
    firebaseApp.auth().signInWithEmailAndPassword(email, password)
          .then((data) => {
            //this.setState({ error: 'Account already exists. Logging you in...', loading: false });
            console.log('success data', data);
            this.setState({
              user: data,
            });
          })
          .catch((data) => {
            //this.setState({ error: 'Authentication failed.', loading: false });
            console.log('error data', data);
          });
  }

  componentDidMount() {
    var geoQuery = geoFire.query({
      center: [45.616422, -122.580453],
      radius: 1000,
      });
    geoQuery.on("key_entered", function(key, location, distance) {
      // dont forget that as shifts are added that match the geo, this will automatically add to the shiftKeys array
      //shiftKeys = [];
      shiftKeys.push(key)
      console.log("Found shift " + key + " at " + location + " (" + distance + " km away)");
    });

    geoQuery.on("ready", () => {
      shifts = []; // we need to blow out the array every time this function runs or it will throw errors
      shiftKeys.forEach((shiftKey) => {
        //console.log(shiftKey);
        let shiftsRef = firebaseApp.database().ref('shifts').child(shiftKey);
        shiftsRef.on("value", (snapshot) => {
          //console.log(snapshot.val())
          //if (snapshot.val().state == "WA" && (snapshot.val().licenseRequired == "CNA" || snapshot.val().licenseRequired == "RN")) {
          //if (snapshot.val().licenseType == this.state.licenseType || snapshot.val().licenseRequired == "TEST") {
          shifts.push({
            key: snapshot.key,
            fname: snapshot.val().fname,
            lname: snapshot.val().lname,
            company: snapshot.val().company,
            address1: snapshot.val().address1,
            address2: snapshot.val().address2,
            city: snapshot.val().city,
            state: snapshot.val().state,
            zip: snapshot.val().zip,
            shiftDate: snapshot.val().shiftDate,
            shiftStart: snapshot.val().shiftStart,
            shiftLength: snapshot.val().shiftLength,
            shiftDescription: snapshot.val().shiftDescription,
            licenseType: snapshot.val().licenseType,
            logo: snapshot.val().logo,
            building: snapshot.val().building,
          }) // end shifts.push
          var date_sort_asc = function (date1, date2) {
            if (date1.shiftDate > date2.shiftDate) return 1;
            if (date1.shiftDate < date2.shiftDate) return -1;
            return 0;
          };
        //}
          //console.log(this.state.distancePref)
          this.setState({
            dataSource: shifts,
            resultCount: shifts.length,
          })
        }); // end shiftsRef.on
      }); // end shiftKeys map
    }); // end geoQuery.on
    console.log('ShiftArray: ', shifts)
    console.log('StateArray: ', this.state.dataSource)
  }


  render() {
    const listItems = this.state.dataSource.map((shift) =>
      <li key={shift.key}>
        {shift.address1}
      </li>
    );
    console.log('ShiftArray: ', shifts)
    console.log('StateArray: ', this.state.dataSource)

    return (
  <Flexbox flexDirection="column" minHeight="100vh">
    <Flexbox element="header" height="60px">
      Header link one
    </Flexbox>

    <Flexbox flexGrow={1}>
      <Flexbox
        width="20%"
        minWidth="200px"
        maxWidth="300px"
        style={{ backgroundColor: '#ba0000' }}>
          Sidebar Menu Goes Here
      </Flexbox>
      <Flexbox width="80%" flexDirection="row" style={{ backgroundColor: '#FFF' }}>
        <div>List of Shifts Addresses</div>
        <ul>{listItems}</ul>
      </Flexbox>
    </Flexbox>

  <Flexbox element="footer" height="60px">
    Footer
  </Flexbox>
</Flexbox>
    );
  }
}

现在我得到了Uncaught TypeError:this.state.dataSource.map不是函数

1 个答案:

答案 0 :(得分:0)

问题是我无法在状态中初始化dataSource,然后我用字符串而不是空数组初始化它。

在构造函数的this.setstate中缺少dataSource: []