繁体   English   中英

如何在 react-redux 中调度 in.then()

[英]How to dispatch in .then() in react-redux

我正在处理我遇到这个问题的项目。 The thing is, I am calling an axios API and after its success I want to update my redux state ie in the .then .then() chain of 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)


这样做之后,我看到相同的 state 没有区别

这是 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和 function 组件

应用程序.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)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM