2017-12-28 9 views
0

this.setState ({device})가 "this.state.device = __"를 사용하지 않으면 상태를 전혀 업데이트하지 않습니다. 구성 요소가 다시 렌더링되지 않으므로 문제가 발생합니다. 나는 같은 콜백 함수를 사용하여 시도 :React Native Redux : this.setState가 상태를 변경하지 않습니다.

this.setState({device: selectedDeviceId},() => { 
    console.log(this.state.device) 
})  

하지만 코드가 setState를도 호출되지 않는 것을 나타냅니다 전혀 기록하지 않습니다.

class Stats extends React.Component { 
    state = { 
    viewType: 'day', 
    dt: moment(), 
    device: {} 
    } 
    getDevice =() => { 
    const devices = this.props.devices || [] 
    const selectedDeviceId = this.props.selectedDeviceId 

    devices.forEach((d) => { 
     if (d._id === selectedDeviceId) this.setState({device: d}) 
    }) 
    if (!this.state.device._id && devices.length) { 
     this.setState({device: devices[0]}) 
    } 
    this.getUsage() 
    } 

    componentWillMount() { 
     console.log('Enter StatsScreen.componentWillMount') 
     let dt = this.state.dt 
     const date = moment(dt).format('YYYY-MM-D') 
     console.log(date) 
     this.getDevice() 
    } 
} 
+0

console.log를 공유 할 수 있습니까? 그리고 if 문이 true로 평가되는지 확인하기 위해 "! this.state.device._id && devices.length"의 값. –

+0

렌더링 기능을 삽입 할 수 있는지 더 많은 아이디어를 줄 것입니다. –

+0

"componentDidMount"가 Stats 클래스 외부에있는 이유는 무엇입니까? –

답변

1

문제는 state라는 변수를 사용하고있는 React Native 상태를 사용하고 있지 않다는 것입니다. 생성자 라이프 사이클 메소드를 작성하고 거기에 this.state =를 넣어 초기화하십시오.

Btw는 willMount 라이프 사이클 메소드에서 이와 같은 일을하지 마십시오. 그러면 didMount에서 UI를 차단하지 않습니다.

+0

나는 행운이없이 이것을 시도했다. 생성자 (소품) {super (props) this.state = {viewType : 'day', dt : moment(), device : {}}} – Lalaluye

+0

didMount의 상태가 고정되었습니다. 고맙습니다! – Lalaluye

관련 문제