This repository was archived by the owner on Jan 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
This repository was archived by the owner on Jan 8, 2019. It is now read-only.
React-Router-Redux在action层中的使用 #13
Copy link
Copy link
Open
Description
一个需求:比如新建文章,发送到服务器后,这时候页面应该有个跳转
PostAction.js
export const SendPostToServer = (title,content)=>{
//post by fetch
}由于整个react组件的改变状态变化的权利都交给了redux,意味着所有必须在action层中完成跳转。
使用react-router-redux提供的api:
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { routerMiddleware, push } from 'react-router-redux'
// Apply the middleware to the store
const middleware = routerMiddleware(browserHistory)
const store = createStore(
reducers,
applyMiddleware(middleware)
)
// Dispatch from anywhere like normal.
store.dispatch(push('/foo'))所以我的代码部分是这样的:
export const SendPostToServer = (title,content)=>{
return (dispatch,getState)=>{
dispatch(RequestPosts());//先表明正在请求
return request.post(`/api/posts`,{title,content},{
headers:{
'Content-Type': 'application/json;charset=utf-8',
'Authorization':`${GetTokenFromStorage()}`
}
})
.then(res=>{
let resStatus=res.data;
if(!resStatus.success){
dispatch(ErrorHandle(resStatus.message));
dispatch(CreateOpenSnackbar());//开启snaker
}else{
dispatch(GetPostSended(resStatus.message));
dispatch(ChangePostsCounts(resStatus.counts));
dispatch(CreateOpenSnackbar());//开启snaker
dispatch(push(`/posts`)); //通过react-router-redux进行切换
}
})
.catch(err=>{
dispatch(ErrorHandle(err.message));
dispatch(CreateOpenSnackbar());//开启snaker
});
}
}完美解决
Metadata
Metadata
Assignees
Labels
No labels