使用Redux和React-router导航页面

时间:2017-08-03 14:38:42

标签: reactjs redux react-router

我有一系列页面来捕获用户的数据。我希望ReduxReact-Router一起使用,以浏览我的网页,而不是手动链接到每个页面。

我有一个非常简单的Router设置。

import Screen1 from './components/Screen1';
import Screen2 from './components/Screen2';
import Screen3 from './components/Screen3';
import Screen4 from './components/Screen4';
import Screen5 from './components/Screen5';
import Screen6 from './components/Screen6';

let store = createStore(lydApp);

render(
    <Router>
        <div>
            <Route path="/" component={Screen1} />
            <Route path="/1" component={Screen2} />
            <Route path="/2" component={Screen3} />
            <Route path="/3" component={Screen4} />
            <Route path="/4" component={Screen5} />
            <Route path="/5" component={Screen6} />
        </div>
    </Router>,
    document.getElementById('root')
);

一个非常基本的reducer

import { NEXT_PAGE, PREVIOUS_PAGE } from '../constants/ActionTypes';

const initialState = [
  {
    title: 'Screen1',
    complete: 0,
  },
  {
    title: 'Screen2',
    complete: 0,
  },
  {
    title: 'Screen3',
    complete: 0,
  },
  {
    title: 'Screen4',
    complete: 0,
  },
  {
    title: 'Screen5',
    complete: 0,
  },
];

export default function PageChecker(state = initialState, action) {
  switch (action.type) {
    case NEXT_PAGE:

    //somehow check page is complete and move to next page

    default:
      return state;
  }
}

如何使用我的NEXT_PAGE操作来浏览我的应用?

1 个答案:

答案 0 :(得分:0)

You can do something like like async action, but you have to have redux-thunk middleare https://github.com/gaearon/redux-thunk attached.

Here's example code:

export default function PageChecker(state = initialState, action) {
  return (dispatch, getState) => {
    switch (action.type) {
      case NEXT_PAGE:

        dispatch(go(`/page/${action.page + 1}`))

        return state;
      break;
      default:
        return state;
    }
  }
}