我已经建立了我的第一个Redux projet,我正试图通过从rails后端获取它来为当前用户创建商店。
尽管一切似乎都很好,但是this.props.user
在组件中提供了null
。
store.js:
import { createStore, applyMiddleware } from "redux";
import thunk from 'redux-thunk';
import rootReducer from "./reducers";
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
export default store;
actions.js
import { CREATE_USER, PROPAGATE_LOGIN, PROPAGATE_LOGOUT } from "./actionTypes";
import axios from 'axios';
export const getCurrentUser = () => {
return dispatch => {
axios.get("/users/get_current_user", {})
.then(response => {
if (response.data.user) {
dispatch(propagateLogin(response.data.user));
} else {
console.log("pas d'utilisateur connecté.")
dispatch(propagateLogout());
}
});
};
};
export const propagateLogin = (user) => ({
type: PROPAGATE_LOGIN,
payload: {
user
}
});
export const propagateLogout = () => ({
type: PROPAGATE_LOGOUT,
payload: { }
});
users.js精简器:
import { CREATE_USER, PROPAGATE_LOGIN, PROPAGATE_LOGOUT } from "../actionTypes";
const initialState = {
user: null
};
export default function(state = initialState, action) {
switch (action.type) {
case PROPAGATE_LOGIN: {
return {
user: action.payload.user
}
}
case PROPAGATE_LOGOUT: {
return {
user: null
}
}
default:
return state;
}
}
AppRouter.js(连接的组件):
class AppRouter extends React.Component {
defaultState() {
return {
isReady: false,
user: this.props.user,
loginModalOpen: false,
signupModalOpen: false
}
}
constructor(props) {
super(props)
this.state = this.defaultState()
}
componentDidMount() {
this.getUser();
}
getUser(history = undefined) {
this.props.getCurrentUser();
this.setState({
isReady: true
});
}
render (){
// [...]
}
};
const mapStateToProps = (state /*, ownProps*/) => {
return {
user: state.users.user
}
}
const mapDispatchToProps = { getCurrentUser, propagateLogout }
export default connect(
mapStateToProps,
mapDispatchToProps
)(AppRouter);
这是React开发者控制台的屏幕截图:Provider
组件:
答案 0 :(得分:1)
在user.js中,reducer用户初始状态为空
const initialState = {
user: null
};
由于获取用户操作是异步的,因此您只是将空值赋给处于初始状态的用户
defaultState() {
return {
isReady: false,
user: this.props.user, //this.props.user null here
loginModalOpen: false,
signupModalOpen: false
}
您可以使用this.props.user而不使用其状态值