2016-07-26 3 views
0

페이지 매김을 만들 때 Redux를 사용하고 있습니다. 내 문제는, constructor URL을 구문 분석하고 페이지 매김에 대한 것이 있는지 확인하는 메소드를 실행했습니다. 그런 다음 데이터를 저장소에 저장하는 작업을 실행합니다. 모두 원활하게 돌아갑니다.React - constructor() 및 componentDidMount

그런 다음 데이터를 가져 오는 다른 작업을 실행할 때 componentDidMount 메서드가 있습니다. 그리고 나는 이전에 강요 한 소품들을 사용합니다. 불행히도, 가게는 초기 상태에 있습니다.

내 (간체) 코드 :

class NewsList extends React.Component { 
    constructor(props) { 
     super(props); 

     this.profile = document.getElementById('articles').getAttribute('data-profile'); 

     this.parseHash(); 
    } 

    parseHash() { 
     /* Method for parsing navigation hash 
     ---------------------------------------- */ 
     const hash = window.location.hash.replace('#', '').split('&'); 

     const data = { 
      page: 1, 
      offset: 0 
     }; 

     // hash parsing 

     this.props.setPagination(data); 
    } 

    componentDidMount() { 
     this.loadNews(); 
     // If I use 
     // setTimeout(() => { this.loadNews(); }) 
     // it works, but I feel this is hack-ish 
    } 

    loadNews() { 
     this.props.update({ 
      current: {page: this.props.NewsListReducer.current.page, offset: this.props.NewsListReducer.current.offset}, 
      next:  {page: this.props.NewsListReducer.next.page, offset: this.props.NewsListReducer.next.offset} 
     }); 
    } 
} 

I console.log(this.props.NewsListReducer), 내가 모두 currentnext 개체에 대한 undefined를 얻고있다,하지만 돌아 오는 DevTools로를 사용하는 경우, 데이터가있다. 내가 무엇을 할 수 있을지?

+0

this.parseHash()를 componentWillMount()로 이동하십시오. – jzm

+0

@jzm과 동일합니다. 'constructor'은'componentWillMount()'의 대체물과 같습니다. –

+1

순수한 반응. 하지만 redux, 여기에 마지막 대답을 참조하십시오 : http://stackoverflow.com/a/37703446/769083 – jzm

답변

0

어딘가에 비동기가있는 것처럼 보입니다. 반응 형 환원제를 사용하고 계신 겁니까? 나는 비동기가 setState when the store state has changed을 사용하기 때문에 connect ed 구성 요소에서 오는 것이라고 생각합니다. setState은 비동기 상태 업데이트를 예약합니다.

따라서 this.props.NewsListReducercomponentDidMount()으로 업데이트되지 않았습니다.

this.props.update은 뉴스를 가져 오는 작업입니다. 맞습니까? 구성 요소의 페이징 정보를 제공해야하는 이유는 무엇입니까? 예 : redux-thunk를 사용하면 작업을 보내기 전에 저장소 상태에 액세스 할 수 있습니다. 이것은 (최신) 페이징 정보를 읽을 수있는 기회입니다.

예.

export function fetchNews() { 
    return (dispatch, getState) => { 
    getState().NewsListReducer.current.page; // Up to date 

    ... 

    fetch(...).then(() => 
     dispatch({...})); 
    } 
} 

btw. 당신의 상태를 *Reducer라고하지 않는 것이 좋습니다. 그것은 국가를 관리하는 감속 원이지만, 감속기는 그런 방식으로 국가의 일부가 아닙니다.

관련 문제