【问题标题】:How to dispatch in .then() in react-redux如何在 react-redux 中调度 .then()
【发布时间】:2021-01-25 10:51:11
【问题描述】:

我正在处理我遇到此问题的项目。问题是,我正在调用 axios API,在它成功后我想更新我的 redux 状态,即在 axios 的.then() 链中。我怎样才能做到这一点?正如我通过应用我所知道的所尝试的那样 -> 我在我的组件中创建了一个 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 做到这一点,但你不需要这样做。在组件中执行请求并在成功时分派一个动作应该没问题,就像你现在正在做的那样。是Signin 组件内部的submitForm 回调吗?你能把组件代码贴在你调用submitForm的地方吗?

标签: javascript reactjs redux react-redux react-redux-form


【解决方案1】:

你可以在react hook中使用redux-thunk和函数组件

App.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

reducer.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
    })
...

action.js

const actionFunc = () => {
    return (dispatch, getState) => {
        return axios({
           //Api details 
        }).then(res => res).catch(err => err)
    }
}

【讨论】:

    猜你喜欢
    • 2018-05-05
    • 2018-09-29
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多