gpt4 book ai didi

javascript - 立即获得 ACTION CREATOR 返回的状态

转载 作者:行者123 更新时间:2023-11-30 11:30:50 25 4
gpt4 key购买 nike

如何在发送 Action 后立即获取状态值?如果是 state,它将像 setState 中的箭头函数一样简单,例如:

this.setState({ test: true }, () => {
console.log("hey im loggin!!"
})

但是如果使用 action creator 会怎么样:例如我在我的连接函数中有这个:

export default connect({mapStateToProps, { loginUser }})(Home);

如何做到这一点?

this.props.loginUser(, () => {
console.log("of course this code does not work")
});

.then() 不工作..

目前我正在使用一个函数并立即注入(inject)到组件中,我觉得这不是正确的做法......像这样:

test() {
this.props.loginUser(email, password);
console.log(this.props.user)
}

在我的组件中

return (<div>{this.test()}</div>)

编辑:顺便说一句,我的操作和 REDUCER

import axios from 'axios';
import { LOGIN, LOGIN_SUCCESS, LOGIN_ERROR } from './types';

const API_URL = 'http://localhost:8000/';

export const loginUser = (email, password) => {
return (dispatch) => {
dispatch({ type: LOGIN })

axios.post(`${API_URL}v1/login`, { email, password })
.then( user => {
dispatch({
type: LOGIN_SUCCESS,
payload: user.data.user })
})
.catch( error => {
dispatch({ type: LOGIN_ERROR, payload: error })
})
};
};

reducer :

import { LOGIN, LOGIN_SUCCESS, LOGIN_ERROR } from '../actions/types';

const INITIAL_STATE = {
loading: false,
user: [],
message: '',
error: false,
};

export default (state = INITIAL_STATE, action) => {
switch(action.type) {
case LOGIN:
return { ...state, loading: true }
case LOGIN_SUCCESS:
return { ...state, loading: false, user: action.payload, error: false, message: '' }
case LOGIN_ERROR:
return { ...state, loading: false, error: true, message: action.payload }
default:
return state
}
};

应用js

<Provider store={createStore(store, {}, applyMiddleware(thunk))}>
<Router>
<div>
<Route exact path="/" component={LoginForm} />
<Route path="/home" component={Home} />
<Route path="/profile" component={Profile} />
</div>
</Router>
</Provider>

最佳答案

我相信这些操作会返回 Promise,因此您可以这样做:

this.props.fetchUser().then(() => {
console.log("do something")
});

请注意,您需要在操作中返回 Promise/dispatch

return axios.post(`${API_URL}v1/login`, { email, password })
.then( user => {
return dispatch({
type: LOGIN_SUCCESS,
payload: user.data.user })
})
.catch( error => {
return dispatch({ type: LOGIN_ERROR, payload: error })
})

关于javascript - 立即获得 ACTION CREATOR 返回的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46296221/

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