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



我正在做一个项目,我被困在这个问题上。问题是,我正在调用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
})

可以在react hook中使用redux-thunk和function组件

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'
}
<<p>组件/strong>
...
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)
}
}

相关内容

  • 没有找到相关文章

最新更新