【问题标题】:Redux: state won't display arrayRedux:状态不会显示数组
【发布时间】:2019-01-19 03:29:47
【问题描述】:

我在一个数据库中有两个示例,其结构如下:

state:
  interaction: [
    {creatorId: 123,
     title: exampleTitle1
    },
    {creatorId: 1234,
     title: exampleTitle2}
  ]

这家店是这样的:

const store = createStore(
  combineReducers({
    ...(other reducers)
    interaction: interactionReducer
  }),
  applyMiddleware(thunk)
);

我根据componentDidMount 从 API 获取基础:

componentDidMount() {
  this.props.dispatch(fetchBases());
}

有了这个动作创建者:

export const BASE_SUCCESS = "BASE_SUCCESS";
export const baseSuccess = bases => ({
    type: BASE_SUCCESS,
    bases,
});

和操作(当我控制台日志action 数组返回就好了):

export const fetchBases = () => dispatch => {
  fetch(`${API_BASE_URL}/base/list`, {
    method: "GET",
  })
  .then(res => {
    if (!res.ok) {
      return Promise.reject(res.statusText);
    }
    return res.json();
  })
  .then(bases => dispatch(baseSuccess(bases)))
  .catch(error => {
    console.log("GET request failed", error);
  });
};

减速器:

export default function interactionReducer(state = initialState, action) {
    if (action.type === BASE_SUCCESS) {
      return Object.assign({}, state, {
        bases: action.bases,
      });
    }
    return state;
}

在组件中,我有以下内容:

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

export default requiresLogin()(connect(mapStateToProps)(DashContent));

当我在组件中控制台日志this.state 时,我得到null 的日志。我无法弄清楚为什么它没有正确填充数据以挽救我的生命。之前它只显示了数组中的一项,但现在它为空

【问题讨论】:

  • this.state?您的组件中是否有任何本地状态。你检查过:this.props.bases
  • 另外,它应该是bases: state.interaction.bases,因为您的全局状态中有一个interaction 状态。

标签: arrays reactjs redux


【解决方案1】:

你应该这样打开你的状态:

const mapStateToProps = state => ({
    bases: state.interaction.bases,
});

因为您在全局状态中有一个 interaction 状态。此外,this.state 无法看到任何状态,因为它指向应用程序的本地状态。您可以使用propsthis.props.bases 来达到您的状态。

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 2021-03-19
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 2021-10-17
    • 1970-01-01
    • 2020-09-18
    相关资源
    最近更新 更多