javascript - 如何在 react-redux 中调度 .then()
问题描述
我正在研究陷入这个问题的项目。问题是,我正在调用一个 axios API,在它成功后我想更新我的 redux 状态,即在.then()
axios 链中。我怎样才能做到这一点?正如我通过应用我所知道的所尝试的那样 -> 我在我的组件中创建了一个 react-redux 调度。我知道如何正常执行此操作,onClick
但在then
方法中我不知道如何触发它。
我试过这样做:
let submitForm = (e) => {
e.preventDefault();
// Axios request
const url = 'http://localhost:5000/api/v1/users/login'
axios({
//Api details
})
.then(res => {
// Store API data in LocalStorage
})
.then(() => {
LogIN(); // Here I want to change redux state //
history.push('/dashboard')
})
}
--Component
function Signin({LogIN}) {
return (
)
}
const mapDispatchToProps = dispatch => {
return {
LogIN: () => dispatch(login_action())
}
}
export default connect(null , mapDispatchToProps)(Signin)
这样做之后,我看到相同的状态没有区别
这是redux:
const login_action = () => {
return {
type : 'LOG-IN'
}
}
const loginLogOutReducer = (state = false, action) => {
switch (action.type) {
case 'LOG_IN':
return !state
default:
return state
}
}
const AllReducers = combineReducers({
isLoggedIn : loginLogOutReducer
})
解决方案
您可以redux-thunk
在反应钩子中使用和功能组件
应用程序.js
import {Provider} from 'react-redux'
import store from './store'
<Provider store={store()}>
<AppComponent />
</Provider>
store.js
import {applyMiddleware, compose, createStore} from 'redux'
import thunk from 'redux-thunk'
import {initialState, rootReducer} from './reducers'
const store = () => {
return createStore(rootReducer, initialState, compose(applyMiddleware(thunk)))
}
export default store
减速器.js
import {actionTypes} from './actionTypes'
const initialState = {}
const rootReducer = (state = initialState, action) => {
if (action.type === actionTypes.STH) {
return {
...state,
sth: action.payload,
}
}
}
export {initialState, rootReducer}
actionTypes.js
export const actionTypes = {
STH: 'STH'
}
零件
...
const onChange = => {
dispatch(actionFunc()).then(res => {
// DO Something
})
...
动作.js
const actionFunc = () => {
return (dispatch, getState) => {
return axios({
//Api details
}).then(res => res).catch(err => err)
}
}
推荐阅读
- python - 在 pandas/python3 之前转换命名聚合
- c++ - 从派生类初始化构造函数的问题
- javascript - 如何在调整大小时关闭滑入式导航栏?
- python - 即使我将变量设置为重新启动它,循环也不会重新启动
- git - 是否有命令将一棵 gitignore 树“卷起”到一个父 gitignore 中?
- kubernetes - 使用 helm 升级(部署 + PVC)到 Statefulset
- mysql - 对于按主键排序时的 Mysql ORDER BY LIMIT 查询,我需要复合索引吗?
- flutter - Fultter GridView 滚动
- mysql - 选择数据时至少过滤一个空记录
- docker - 如何访问历史泊坞窗'
' 图片