代码之家  ›  专栏  ›  技术社区  ›  Chris Chong

如何将状态值插入函数?

  •  0
  • Chris Chong  · 技术社区  · 7 年前

    我想将其保存在状态中,以便在数据更改时重新渲染屏幕。

    我似乎无法将状态的值引入到我的函数中。如果我从数组中输入值,它会工作,但当数据更改时,它不会自动重新渲染。

    enter image description here

    这里有一个错误 enter image description here

    它应该在101行左右,但我无法找到正确的语法使thsi工作。

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

    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>
        );
      }
    }
    

    现在我得到了未捕获的类型错误:这个。状态数据源。地图不是一个函数

    1 回复  |  直到 7 年前
        1
  •  0
  •   Chris Chong    7 年前

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

    缺少: dataSource: [] 在这方面。在构造函数中设置状态。