我正在使用Redux。我能够从api中获取数据,但是当我尝试更新reducer时。它不会更新它,并且在道具中显示空值。
我通过设置初始状态尝试了不同类型的编码,并尝试与之保持一致。
主文件(App.js)
const store = configureStore();
export default class App extends Component<Props> {
render() {
return (
<Provider store={store}>
<AppContainer/>
</Provider>
);
}
}
Store.js
import {createStore, combineReducers, applyMiddleware, compose} from 'redux';
import authReducer from './src/reducers/authReducer';
import thunk from 'redux-thunk';
const storeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const rootReducer = combineReducers({
user: authReducer,
});
const configureStore = () => {
return createStore(rootReducer, storeEnhancers(applyMiddleware(thunk)));
};
export default configureStore;
Auth.js
import {USER_AUTH,} from './types';
import api from './../api/auth';
import axios from "axios";
const URL = 'Some URl';
export const login = credentials => (dispatch) =>
axios.get(URL)
.then(user => {
dispatch(userLoggedIn(user))
}).catch(err => {
console.log(err, 'er');
});
export const userLoggedIn = (user) => {
return {
type: USER_AUTH,
user
}
};
authReducer.js
import { USER_AUTH } from '../actions/types';
const initialState = {
user: []
};
const authReducer = (state = initialState, {type, user}) => {
switch (type) {
case USER_AUTH:
// console.log(user) I have data here but not updated when I call it.
return Object.assign({}, state, {
user: state.user.concat(user)
});
default:
return state;
}
};
export default authReducer;
反应文件
const mapStateToProps = state => {
return {
user: state.user
}
};
const mapDispatchToProps = dispatch => {
return {
login: (credentials) => {
dispatch(login(credentials))
}
}
};
export default connect(mapStateToProps, mapDispatchToProps)(LoginForm)
单击按钮时将调用以下功能登录。
this.props.login(credentials);
console.log(this.props, 'props'); // when I do console user is empty not updated.