如何在发出行动后立即获得州的价值?如果是state,它将像setState中的箭头函数一样简单,如:
this.setState({ test: true }, () => {
console.log("hey im loggin!!"
})
但是如果使用动作创建者呢:例如我在我的连接函数中有这个:
export default connect({mapStateToProps, { loginUser }})(Home);
怎么这样做?
this.props.loginUser(, () => {
console.log("of course this code does not work")
});
.then()不起作用..
currenty我正在使用一个函数,并立即注入组件,这是我觉得不正确的事情......就像这样:
test() {
this.props.loginUser(email, password);
console.log(this.props.user)
}
在我的组件中
return (<div>{this.test()}</div>)
编辑:我的行动和减少btw
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 })
})
};
};
reduer:
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
}
};
app 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>
答案 0 :(得分:2)
我相信这些行动会返回Promise,所以你可以这样做:
this.props.fetchUser().then(() => {
console.log("do something")
});
请注意,您需要在行动中退回承诺/发送
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 })
})
答案 1 :(得分:1)
以下步骤可能会对您有所帮助 -
使用redux-thunk
import { Provider } from 'react-redux';
import { createStore,combineReducers, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import reducers from './reducers';
let reducer = combineReducers(reducers)
// applyMiddleware supercharges createStore with middleware:
const createStoreWithMiddleware = createStore(reducer, applyMiddleware(thunkMiddleware))
ReactDOM.render(
<Provider store={createStoreWithMiddleware}>
<App />
</Provider>,
document.getElementById('root')
);
仅举例 -
export function fetchUser(userId) {
return dispatch => {
return Api.fetchUser(userId)
.then( res => {
dispatch(updateUserDetail(res));
});
};
}
Api.fetchUser
是您的axios调用的抽象,以获取用户详细信息。
export function updateUserDetail(userRes) {
return {
type : UPDATE_USER_DETAILS,
userRes
};
}