2017-09-14 6 views
0

firebase 데이터베이스 쿼리에서 생성 된 배열이 있습니다.상태에서 값을 함수에 삽입하는 방법은 무엇입니까?

데이터를 변경하면 화면을 다시 렌더링 할 수 있도록 상태로 저장하려고합니다.

상태에서 값을 내 함수로 가져올 수 없습니다. 배열에서 값을 넣으면 작동하지만 데이터가 변경되면 자동으로 다시 렌더링되지 않습니다.

배열을 사용한 스크린 샷 ... 콘솔 로그가 상태가 올바르게 설정되었음을 표시합니다. 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: '[email protected]', 
     dataSource: '' 
    }; 
    } 
    componentWillMount() { 
    let email = '[email protected]'; 
    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> 
    ); 
    } 
} 

이제 임은 확인되지 않은 유형 : this.state.dataSource.map이

+0

또는 어쩌면 잘못된 접근 방식으로 시작하는 상태로 설정된 배열을 루프 할 수 있습니까? –

+0

상태를 초기화했는지 확인하십시오. 데이터를 가져 오는 데 시간이 걸립니다. 다음 예제와 같이 조건부 렌더링을 수행 할 수도 있습니다. https://stackoverflow.com/questions/46143513/how-to-display-data-from-api-in-react-component/46143565#46143565 최소한 중지해야합니다. 구성 요소가 충돌하는 것입니다. 그러나 더 많은 도움을 얻으려면 더 많은 논리를 가져와야합니다. 어디 있니? 'componentDidMount'에? – jonahe

+0

그게 도움이되었지만 지금은 다른 오류 : 잡히지 않은 TypeError : this.state.dataSource.map은 함수가 아닙니다. 코드를 게시합니다. –

답변

0

문제는 내가 상태에서 dataSource를 초기화하는 데 실패하고 그 후, 나는 그것을 초기화이었다 함수 아니다 빈 배열 대신 문자열을 사용합니다.

누락되었습니다 : 생성자 this.setstate에 dataSource: [].

+0

다행이었습니다. 어쩌면 당신은 이미 이것을 알고있을 것입니다, 그러나 당신은 당신의 대답을 받아 들일 수 있습니다 (48 시간 후). https://stackoverflow.com/help/self-answer – jonahe

관련 문제