2016-06-19 4 views
2

나는 이것을 잠시 동안 알아 내려고 노력해 왔으며 점점 더 혼란스러워지고 있습니다.경로 변경시 Redux 상태 업데이트

나가거나 경로를 변경할 때마다 Redux 상태를 재설정/변경하고 싶습니다. 나는 모든 시간 경로가 변경 작업

history.listen(location => store.dispatch(resetManualsCategory())); 
을 파견 history.listenerreact-router-redux을 사용하고

행동 작성자 :

export function resetManualsCategory() { 
    return { 
     type: 'RESET_MANUALS_CATEGORY' 
    } 
} 

감속기

export function manualCategories(state=[], action) { 
    switch (action.type) { 
     case 'SELECT_MANUALS_CATEGORY': 
      [...] 

     case 'RESET_MANUALS_CATEGORY': 
      console.log('test reducer'); 
      return Object.assign({}, state, { 
       manualCategory: 'test' 
      }) 

     default: 
      return state 
    } 
} 

나를 가장 혼란 무엇 , 페이지를 새로 고치거나 최상위 탐색에서 경로를 두 번 클릭하면 상태가 업데이트되지만 동작 및 감속기가 작동 (콘솔에 테스트 메시지를 표시)하더라도 단일 경로 변경은 redux 상태에 영향을주지 않습니다.

내가 뭘 잘못하고 있고 실제로 무슨 일이 일어나고있는거야?

답변

9

react-router-redux은 모든 경로 변경시 이미 전달 된 LOCATION_CHANGE 액션을 제공합니다. 당신은 간단하게 할 수 있습니다 :

import { LOCATION_CHANGE } from 'react-router-redux' 

export function manualCategories(state=[], action) { 
    switch (action.type) { 
     case LOCATION_CHANGE: 
      /* 
       action.payload is something like: 
       { 
       pathname: '/', 
       search: '', 
       hash: '', 
       state: null, 
       action: 'PUSH', 
       key: 'xwl8yl', 
       query: {}, 
       $searchBase: { 
        search: '', 
        searchBase: '' 
       } 
       } 
      */ 

     default: 
      return state 
    } 
} 
+0

은''@@ router/LOCATION_CHANGE''와 같은''LOCATION_CHANGE''입니까? – spik3s

+0

예. 또한 '@@ router/LOCATION_CHANGE'를 사용할 수도 있지만 권장하지는 않습니다. –

+0

방금 ​​문제의 원인을 파악했으며이 질문과 약간 다릅니다. 어쩌면 너 도움이 될 수 있니? http://stackoverflow.com/questions/37912180/react-router-redux-takes-two-clicks-on-a-link-to-update-location-state – spik3s

4

나는 경로를 변경할 때 상태를 재설정하기 위해 다른 접근법을 사용했습니다. 내역/라우터를 청취하는 대신 내 페이지 컨테이너에 componentWillMount 이벤트를 사용하여 '페이지 재설정'작업을 전달했습니다. 예 :

라우터 :

<Provider store={store}> 
    <Router history={history}> 
    <Route path="/page1" component={Page1Container} /> 
    <Route path="/page2" component={Page2Container} /> 
    </Router> 
</Provider> 

페이지 1 컨테이너 :

class Page1Container extends Component { 

    componentWillMount() { 
    this.props.resetPage() 
    } 

    render() { 
    // render Page1 
    } 
} 

const mapStateToProps = (state) => { 
    return { 
    // ... 
    } 
} 

const mapDispatchToProps = (dispatch) => { 
    return { 
    // ... 
    resetPage:() => { dispatch({type: 'PAGE1_RESET_PAGE'}) } 
    } 
} 

export default connect(mapStateToProps, mapDispatchToProps)(Page1Container) 

감속기 :

const initialState = null 

export function Page1Reducer (state = initialState, action) { 
    switch (action.type) { 
    case 'PAGE1_RESET_PAGE': { 
     state = initialState 
     break 
    } 

    // ... 
    } 
} 
+0

이것은 어떤 이유로 든 사용 된 구성 요소의 상태 (들)를 다시 설정하기 만하면 좋은 해결책이 될 것 같습니다. – MattD

0

은 현재 내가이 일을 componentWillUnmount()의 사용을 만들고있어. 나는 그 상태를 재설정하기 위해 재설정하려고하는 감속기에 조치 설정을 가지고 있으며, componentWillUnmount() 메소드에서 조치를 전달합니다.

React Router를 사용할 때 경로 변경으로 새로 고침이 실행되지 않고 동일한 경로에서 구성 요소가 다시 탑재되지 않으므로 예를 들어 게시물/신규 및 게시물/edit/: id 두 경로를 모두 사용하여 동일한 구성 요소를 사용하여 게시물을 수정하면 경로 사이를 이동해도 구성 요소가 다시 탑재되지 않습니다. 이 때문에 componentWillUnmount의

는()하지 실행, 동일한 구성 요소는 새로운 소품을받을 것입니다. 따라서 componentWillReceiveProps (newProps)을 사용하여 비교 작업을 수행하고 그에 따라 업데이트 할 수 있습니다.

강제로 구성 요소를 다시 마운트하려면 다시 마운트하려는 구성 요소의 키 특성이 다른지 확인해야합니다. 자세한 내용은 herehere을 참조하십시오.

관련 문제