【问题标题】:Redux - initializing the state with async dispatchRedux - 使用异步调度初始化状态
【发布时间】:2019-01-29 16:12:05
【问题描述】:

我有一个应用程序,它为我提供有关请求静态文件的用户详细信息(所以一开始 - 我不必登录)。我尝试使用异步操作检查用户是否有权查看应用程序来初始化状态。但是我的 Auth 组件(将 App 作为子组件)不会在更改的道具上重新渲染。 店铺:

const store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

store.dispatch(fetchUser());

export default store;

在商店中,我在初始化时调度一个异步操作。

动作:

export const fetchUser = () => async dispatch => {
  const response = await axios.get('/api/user/information');

  dispatch({
    type: FETCH_USER,
    payload: response.data
  });
};

然后将动作传递给reducer:

减速器:

export const userReducer = (state = {}, action) => {
  switch (action.type) {
    case FETCH_USER:
      return { ...state, user: action.payload };
  }
  return state;
};

然后将来自 reducer 的数据传递给 Auth 组件。

身份验证组件:

class Auth extends Component {
  public render() {
    return this.props.user ? this.props.children : <p>Access denied</p>;
  }
}

export default compose(Connectable)(Auth);

props 是从 connectablr hoc 传递过来的。

和可连接的 hoc:

const mapStateToProps = (state) => ({
  user: state.user
});

const mapDispatchToProps = {};

export const Connectable = connect(
  mapStateToProps,
  mapDispatchToProps
);

所以应用程序只是停留在“拒绝访问”,因为用户对象是空的。更重要的是 - 当数据被获取时,“用户”道具有另一个嵌套的“用户”对象,然后就有数据了。我想检查用户是否不为空(并修复双用户嵌套对象)。但我不知道为什么更改后的道具不会重新渲染身份验证应用程序。可能是什么原因?初始化状态时不能做异步动作吗?

【问题讨论】:

  • rootReducer 是否结合了userReducer
  • 不,它结合了 userReducer 作为用户,所以这就是双重嵌套的原因。
  • 我认为你不需要Connectable,它是多余的。

标签: javascript reactjs redux redux-thunk


【解决方案1】:

state.user 更改为state.userReducer.user

const mapStateToProps = (state) => ({
  user: state.userReducer.user
});

你的减速器设计可以更好。

https://egghead.io/courses/getting-started-with-redux

export const userReducer = (state = {}, action) => {
  switch (action.type) {
    case FETCH_USER:
      return { ...state, user: action.payload };
  }
  return state;
};

如果你想要初始化用户,我给你一个例子。

import * as actions from '../../actions';

const mapStateToProps = (state) => ({
  user: state.user
});

export const Connectable = connect(
  mapStateToProps,
  actions
);

class Auth extends Component {
 componentDidMount() {
     this.props.fetchUser()
 }
 render() {
    return this.props.user ? this.props.children : <p>Access denied</p>;
  }
}

export default compose(Connectable)(Auth);

【讨论】:

  • 这是什么问题?
  • 我不确定它为什么会出现问题。我没有变异状态。你能说得具体点吗?
  • 你的状态树很大。像 userReducer,如果你的用户有效负载需要一些过程会很困难。
  • 问题:为什么初始化状态时做不到?为什么需要在Auth组件的componentDidMount方法中完成?
猜你喜欢
  • 1970-01-01
  • 2016-09-22
  • 1970-01-01
  • 2016-09-20
  • 1970-01-01
  • 2022-11-12
  • 2017-10-23
  • 2020-05-21
  • 2020-02-22
相关资源
最近更新 更多