路线更改时更新Redux状态

spi*_*k3s 6 reactjs redux react-router-redux

我一直试图弄清楚这一点,我越来越困惑.

我想在每次离开或改变路线时重置/改变Redux状态.我使用react-router-reduxhistory.listener调度的动作,每次路由变化

history.listen(location => store.dispatch(resetManualsCategory()));
Run Code Online (Sandbox Code Playgroud)

行动创造者:

export function resetManualsCategory() {
    return {
        type: 'RESET_MANUALS_CATEGORY'
    }
}
Run Code Online (Sandbox Code Playgroud)

减速器

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
    }
}
Run Code Online (Sandbox Code Playgroud)

令我困惑的是,如果我刷新页面或在顶部导航中的路线上单击两次,状态会更新,但是单个路径更改不会影响redux状态,即使操作和reducer触发(显示测试消息)控制台).

我做错了什么,这里到底发生了什么?

Die*_*Haz 14

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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案不再起作用了。react-router-redux 已重命名为connected-react-router,并且看起来不再以相同的方式工作。 (2认同)

Ale*_*exM 6

更改路线时,我使用了不同的方法来重置状态。我没有监听历史记录/路由器,而是componentWillMount在页面容器上使用事件来调度“重置页面”操作。例:

路由器:

<Provider store={store}>
  <Router history={history}>
    <Route path="/page1" component={Page1Container} />
    <Route path="/page2" component={Page2Container} />
  </Router>
</Provider>
Run Code Online (Sandbox Code Playgroud)

Page1容器:

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)
Run Code Online (Sandbox Code Playgroud)

减速器:

const initialState = null

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

    // ...
  }
}
Run Code Online (Sandbox Code Playgroud)