0

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

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

商店是这样的:

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

我从 API 获取基础componentDidMount

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. 我无法弄清楚为什么它没有正确填充数据以挽救我的生命。早些时候它只显示了数组中的一项,但现在它为空

4

1 回答 1

0

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

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

因为你interaction在全球有一个状态。此外,您看不到任何状态,this.state因为它指向您应用的本地状态。props您可以使用as到达您的状态this.props.bases

于 2018-08-12T00:58:22.837 回答