首页 > 解决方案 > 如何在 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
})

标签: javascriptreactjsreduxreact-reduxreact-redux-form

解决方案


您可以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)
    }
}

推荐阅读