2017-02-01 4 views
1

homespun json API (json-server --watch db.json)를 사용하여 플럭스 저장소의 상태를 채우려고합니다. 부모 컴포넌트의 componentWillMount에서 Store 함수를 호출하여 Axios로 데이터를로드합니다.액시즈를 통해 상태를 채우는 데 문제가 발생했습니다.

내가 참조를 위해 다음 튜토리얼에서 찾고있다 : http://mediatemple.net/blog/tips/loading-and-using-external-data-in-react/ https://www.toptal.com/react/tips-and-practices 등을. 여기

내가 당기는 오전 JSON 데이터이다

import { EventEmitter } from 'events' 
import dispatcher from '../dispatcher' 
import axios from 'axios' 

import uuid from 'uuid4' 

class TodoStore extends EventEmitter { 
    constructor() { 
    super() 
    this.state = { 
     todos: [], 
     showCompletedTodos: true, 
     showIncompletedTodos: true 
    } 

    this.deleteTodo = this.deleteTodo.bind(this) 
    this.toggleTodo = this.toggleTodo.bind(this) 
    this.toggleShowCompletedTodos = this.toggleShowCompletedTodos.bind(this) 
    this.toggleShowIncompletedTodos = this.toggleShowIncompletedTodos.bind(this) 
    } 
... 

fetchUserState() { 
    let th = this 
    console.log(th) 
    this.serverRequest = 
     axios.get('http://localhost:3000/todos') 
     .then(function(result) { 
      console.log(result.data) 
      th.state.todos = result.data 
     }) 
    } 

} 

const todoStore = new TodoStore 
dispatcher.register(todoStore.handleActions.bind(todoStore)) 

export default todoStore 

요점 :

[ 
    { 
    "complete": "false", 
    "edit": "false", 
    "id": "uuid()", 
    "text": "Go Shopping" 
    }, 
    { 
    "complete": "false", 
    "edit": "false", 
    "id": "uuid()", 
    "text": "Pay Water Bill" 
    } 
] 

db.json 요지 여기

https://gist.github.com/WebRuin/548f6073ca533016503d34c36116b8de 내가 부르고 플럭스 저장소 발췌 인 전체 파일 중 https://gist.github.com/WebRuin/efbbf4296c566f6eb58cc6d641bee4ba

콘솔 로깅을 통해 축 데이터 요청이 원하는 데이터로 완료되고 이 채워지는 것으로 표시되는 this의 로그가 표시되지만 Chrome의 반응 플러그인에는 데이터가 표시되지 않으므로 앱에 데이터가 표시되지 않습니다.

내가 뭘 잘못하고 있니?

+0

"th.state.todos = result.data"대신 "th.setState ({todos : result.data})"시도하십시오. –

+0

아주 좋은 질문입니다. – prosti

답변

2

Andy가 맞습니다. 생성자를 제외하고 항상 상태를 설정할 때 비동기 적으로 작동하는 을 사용해야합니다.


here에서

: 1


2 그러나 이것은 일반적인 반응 마찬가지입니다. Flux에서는 setState 메서드를 잊어 버리고 그냥 상점에서 작업해야합니다. 이 기사의 메시지입니다.

Flux 탐색을 위해 하나의 이미지를 만들었습니다.


enter image description here

일반적으로 당신이하지 componentWillMount() 통해 Axios의를 통해 데이터를로드한다, 그러나 당신은 그것을 위해 흐름 플럭스 작업을 사용할 수 있습니다. 그래도 componentWillMount()을 사용하여 작업을 만들 수 있습니다.

+0

위대한 관점이 추가되었습니다. 고마워, 그래도 확실하지 않아요 this.setState를 EventEmiter로 만든 저장소에서 사용하는 방법 – Tithos

+0

Git hub it. 예제가 있어야합니다. @Tithos – prosti

+0

https://github.com/WebRuin/flux-todo – Tithos

1

상태 개체를 직접 수정하지 마십시오. 항상 setState()을 사용하십시오.

+0

'this.setState'는'EventEmitter'에서 호출 할 수 있습니다. 나는 전에 그것에 뛰어 들었다. 제한된 경험으로'this.setState'는'React.Component '나'React.creatClass '에서만 호출 할 수 있습니다. – Tithos

+0

'this.setState'는'EventEmitter'에서 호출 할 수 없습니다. – Tithos

+0

코드는'fetchUserState '어떤 구성 요소 클래스에있다 –

관련 문제