react.js - react-router-redux在react-router成为4.0后是不是不需要了

查看:122
本文介绍了react.js - react-router-redux在react-router成为4.0后是不是不需要了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

本来在项目打算使用如下的配置,本人通过一些教程中看到了如果想要用react router和redux结合使用的话需要如下的依赖,但是当我从官网的create-creact-app搭建的一个项目中发现了browserHistory这个依赖已经没有了。然后同样的有一个react-router-dom中有一个BrowserRouter这个组件是可以实现相同的,是不是不需要react-router-redux进行router和store同步了啊

import { Router, Route, browserHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux';

解决方案

是的。而且在react-router V3也可以不用react-router-redux。这里我说下V3版本如何同步histroystore。不BB,直接上代码:

import { browserHistory } from 'react-router'
import { createStore } from 'redux'

// action
function locationChange (location = '/') {
  return {
    type    : 'LOCATION_CHANGE',
    payload : location
  }
}

// reducer
const initialState = browserHistory.getCurrentLocation()
function locationReducer (state = initialState, action) {
  return action.type === 'LOCATION_CHANGE'
    ? action.payload
    : state
}

// store
const store = createStore(locationReducer)

const updateLocation = ({ dispatch }) => {
  return (nextLocation) => dispatch(locationChange(nextLocation))
}

//绑定browserHistory,取消绑定执行store.unsubscribeHistory()
store.unsubscribeHistory = browserHistory.listen(updateLocation(store))

这篇关于react.js - react-router-redux在react-router成为4.0后是不是不需要了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆