使用redux,react在纯函数中触发react-router-dom页面跳转

22次阅读

共计 1592 个字符,预计需要花费 4 分钟才能阅读完成。

文章有错误和不合理的地方欢迎小伙伴轻拍看到标题,很多 react 选手可能就会笑了,这还是问题吗?在函数中触发页面跳转不就的用 redux 吗!或者 redux 类似的控件,mbox,dva,rxjs 等等,或者自己写个订阅功能的控件,可能就是因为太简单了,网上的解决这个问题的文章才那么少。当我试着用 react 搭建前端框架,这个问题确实困扰了我好久,当接触到 redux 就是这 redux 是正解了。
痛点
这就是困扰我的问题
对 fetch() 进行封装,并对请求的返回数据做拦截,当捕捉到错误的时候,判断错误的状态码,404 时让页面跳转到 404 页面,当时 401 时跳转到登录页面,500 调整到 500 页面。
react-router ^4 并没有暴露出来 history 对象,这让非组件内页面跳转变的困难。
问题的解决
定义 store
function navTo(state = “/”, action) {
switch (action.type) {
case ‘NAV_TO’:
return action.path;
default:
return state
}
}

let store = createStore(combineReducers({navTo}));
export default store;
fetch() 状态拦截代码
import store from “../../redux/store”;
fetch(builUrl(url, params), requestInit)
.then(data => {
return data.json()
}).catch(e => {
const status = e.name;
if (status === 401) {
store.dispatch({type: ‘NAV_TO’, path: ‘/login’});
return;
}
if (status === 403) {
store.dispatch({type: ‘NAV_TO’, path: ‘/exception/403’});
return;
}
if (status <= 504 && status >= 500) {
store.dispatch({type: ‘NAV_TO’, path: ‘/exception/500’});
return;
}
if (status >= 404 && status < 422) {
store.dispatch({type: ‘NAV_TO’, path: ‘/exception/404’});
return;
}
})
app.js 实现对 store 的订阅,并跳转页面
import React, {Component} from ‘react’;
import store from ‘./app/common/redux/store.js’
import {withRouter} from “react-router-dom”;
@withRouter
class App extends Component {

constructor(props) {
super(props);
store.subscribe(() => {
this.props.history.push(store.getState().navTo);
});
}

render() {
return (
<div>
{this.props.children}
</div>
);
}
}

export default App;
当 fetch() 拦截到错误就可以进行页面调整了如果对 redux 有疑问,可以看我另一篇文章 https://segmentfault.com/a/11…
这就是在函数中通过订阅的方式来实现页面跳转,easy easy !!! 小伙伴可以举一反三运用到更多的地方去!!
???????????????????? 如果能帮助到小伙伴的话欢迎点个赞???????????????????????????????????????? 如果能帮助到小伙伴的话欢迎点个赞????????????????????

正文完
 0