gpt4 book ai didi

javascript - Redux 存储在 React 类组件中返回 null 值

转载 作者:行者123 更新时间:2023-12-03 00:26:11 27 4
gpt4 key购买 nike

我已经设置了我的第一个 Redux 项目,并且我正在尝试通过从 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 reducer :

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 组件:

enter image description here

最佳答案

正如您在 user.js reducer 中编写的那样,用户初始状态为 null

const initialState = {
user: null
};

由于获取用户操作是异步的,因此您只是在初始状态下将 null 值分配给用户

 defaultState() {
return {
isReady: false,
user: this.props.user, //this.props.user null here
loginModalOpen: false,
signupModalOpen: false
}

您可以使用 this.props.user 而无需为其分配状态值

关于javascript - Redux 存储在 React 类组件中返回 null 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54079399/

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