Javascript 无法在ComponentDidMount中使用redux数据

Javascript 无法在ComponentDidMount中使用redux数据,javascript,reactjs,redux,Javascript,Reactjs,Redux,我正在制作一个react redux站点 我正在通过redux访问从api调用的数据 我知道ComponentDidMount不会等待调用此数据,因此我想知道如何更好地将父组件中的此数据拆分为子组件的数组(或者如果此方法是一个错误的选择) 这是一个组成部分,希望能对正在发生的事情有所帮助 import React, { Component } from "react"; import PropTypes from "prop-types"; import

我正在制作一个react redux站点

我正在通过redux访问从api调用的数据

我知道ComponentDidMount不会等待调用此数据,因此我想知道如何更好地将父组件中的此数据拆分为子组件的数组(或者如果此方法是一个错误的选择)

这是一个组成部分,希望能对正在发生的事情有所帮助

import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { fetchPosts, fetchItins } from "../../../actions/postActions";
import TravelAlerts from "./TravelAlerts//travelAlert";
import IntelligenceAlerts from "./IntelligenceAlerts/IntelligenceAlert";
import AllAlerts from "./AllAlerts/AllAlerts";

class Alerts extends Component {
  state = {
    showAllAlerts: true,
    showAllIntelligenceAlerts: false,
    showAllTravellers: false,
    currentPage: 1,
    alertsPerPage: 20,
    travelAlerts: [],
    intelligenceAlerts: [],
  };
  
  componentDidMount() {
    this.props.fetchPosts();
    console.log(this.props.posts);
 

    for (var key in this.props.posts) {
      if (this.props.posts.hasOwnProperty(key)) {
        if (key === "travelAlerts") {
          alert("travel ALerts Hit");
        } else if (key === "intelligenceAlerts") {
          alert("intelligenceAlertsHIts");
        } else {
        }
        console.log(key + " -> " + this.props.posts[key]);
      }
    }
  }

  //navigation helper
  DisableAlerts() {
    this.setState({
      showAllAlerts: false,
      showAllIntelligenceAlerts: false,
      showAllTravellers: false,
    });
  }

  //pagination change page
  handleClick(number) {
    this.setState({
      currentPage: number,
    });
  }
  ToogleAlertType(name) {
    this.DisableAlerts();

    if (name === "All") {
      this.setState({ showAllAlerts: true });
    } else if (name === "Intelligence") {
      this.setState({ showAllIntelligenceAlerts: true });
    } else if (name === "Travellers") {
      this.setState({ showAllTravellers: true });
    } else {
      this.setState({ showAllAlerts: true });
    }
  }
  render() {
    return (
      <div>
        <button
          style={{ width: "30%" }}
          onClick={() => this.ToogleAlertType("ALL")}
        >
          ALL{" "}
        </button>
        <button
          style={{ width: "30%" }}
          onClick={() => this.ToogleAlertType("Intelligence")}
        >
          Intelligence{" "}
        </button>
        <button
          style={{ width: "30%" }}
          onClick={() => this.ToogleAlertType("Travellers")}
        >
          Travellers
        </button>
        <br />
        <hr />

        <div>
          {this.state.showAllAlerts ? (
            <>{/* <AllAlerts alerts={this.props.posts} /> */}</>
          ) : (
            <></>
          )}
        </div>

        <>
          {this.state.showAllTravellers ? (
            <>
              <></>
              {/* <TravelAlerts alerts={this.props.posts} /> */}
            </>
          ) : (
            <></>
          )}
        </>
        <>
          {this.state.showAllIntelligenceAlerts ? (
            <>{/* <IntelligenceAlerts alerts ={this.props.posts}/> */}</>
          ) : (
            <></>
          )}
        </>
      </div>
    );
  }
}
Alerts.propTypes = {
  fetchPosts: PropTypes.func.isRequired,
  posts: PropTypes.object.isRequired,
  // newPost: PropTypes.object
};
const mapStateToProps = (state) => ({
  posts: state.posts.items,
  // newPost: state.posts.item
});

export default connect(mapStateToProps, { fetchPosts })(Alerts);

然而,数据在挂载时不会显示(在render方法中工作,但我觉得这不是一个放置它的好地方)

这是一个很好的方向,还是我应该在它们到达组件之前将它们分成两个单独的阵列?如果是这样,这应该在减速器中还是在动作中进行

非常感谢您的帮助,因为我是redux的新手

编辑 这是我的回帖

export const fetchPosts = () => (dispatch) => {
  fetch(
    "the url im using"
  )
    .then((res) => res.json())
    .then((posts) =>
      dispatch({
        type: FETCH_POSTS,
        payload: posts,
      })
    );
};
我的减速机

import { FETCH_POSTS, NEW_POST, FETCH_ITINS } from "../actions/types";

const initialState = {
  items: {},
  item: {},
  itins: [],
};

export default function (state = initialState, action) {
  switch (action.type) {
    case FETCH_POSTS:
      return {
        ...state,
        items: action.payload,
      };
    case NEW_POST:
      return {
        ...state,
        item: action.payload,
      };
    case FETCH_ITINS:
      return {
        ...state,
        itins: action.payload,
      };
    default:
      return state;
  }
}


不清楚您的fetchPosts在做什么更新了问题:)如果调用
this.props.fetchPosts()
将更改
this.props.posts
,React将调用
componentDidUpdate(…)
,因为props已更改。另外,
fetch()
是异步的,但即使不是,React也不会再次调用
componentDidMount
。Chris G.我把它放进了一个组件并进行了更新,它工作了。如果你想写一个答案,我会把它标记为答案,否则我会把我的答案贴出来。
import { FETCH_POSTS, NEW_POST, FETCH_ITINS } from "../actions/types";

const initialState = {
  items: {},
  item: {},
  itins: [],
};

export default function (state = initialState, action) {
  switch (action.type) {
    case FETCH_POSTS:
      return {
        ...state,
        items: action.payload,
      };
    case NEW_POST:
      return {
        ...state,
        item: action.payload,
      };
    case FETCH_ITINS:
      return {
        ...state,
        itins: action.payload,
      };
    default:
      return state;
  }
}