gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:54:05 25 4
gpt4 key购买 nike

我正在做一个遇到这个问题的项目。问题是,我正在调用一个 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和函数组件

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

关于javascript - 如何在 react-redux 中调度 .then(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65883280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com