Как обновить реквизиты в нижних компонентах в React из магазина Redux? - PullRequest
0 голосов
/ 28 января 2020

У меня возникла путаница по поводу того, как обновлять атрибуты в компонентах в структуре React с использованием состояния Redux. В React меня научили иметь родительский компонент, контейнер ниже, чтобы перебирать массив, а затем передавать каждый компонент компоненту для отображения в DOM. Теперь, когда я использую Redux для управления State, мне интересно, как я могу немедленно изменить атрибут в карточке при обновлении? Разве не достаточно mapStateToProps в родительском компоненте и передать их вниз? Или мне нужно подключиться к магазину в нижнем компоненте, чтобы отразить немедленное изменение состояния?

Вот мой код.

Родительский компонент:

import React, { Component } from "react";
import RecurringOutagesContainer from "./containers/RecurringOutagesContainer";
import FutureOutagesContainer from "./containers/FutureOutagesContainer";
import CurrentOutagesContainer from "./containers/CurrentOutagesContainer";
import CreateModalComponent from "./components/CreateModalComponent";
import { Container, Row, Col, Image } from "react-bootstrap";
import { getFutureOutages } from "./actions/fetchFutureOutagesAction";
import { getRecurringOutages } from "./actions/fetchRecurringOutagesAction";
import { getServices } from "./actions/fetchServicesAction";
import { connect } from 'react-redux'; 


class Dashboard extends Component {
  state = {
    services: [],
    outages: [], 
    showModal: false
  };

  componentDidMount() {
    this.props.getFutureOutages()
    this.props.getRecurringOutages()
    this.props.getServices()
  }


  render() {
    console.log(this.props)
    return (
      <div>
        <Container>
          <Row>
            <Col sm={1}>
              <img
                src={require("./public/logo-2-dashboard.png")}
                alt="logo"
                id="logo"
              ></img>
            </Col>
            <Col md={8}></Col>
          </Row>
        </Container>
        <div className="container">
          <div className="d-flex justify-content-md-end bd-highlight">
            <CreateModalComponent
              show={this.state.showModal}
              services={this.props.services}
              futureOutages={this.props.futureOutages}
              recurringOutages={this.props.recurringOutages}
            />
          </div>
        </div>
        <div className="d-flex justify-content-center bd-highlight dashboard">
          <div className="d-flex justify-content-start bd-highlight">
            <div className="d-fliex pastOutages">
              <h4>Past Outages</h4>
            </div>
          </div>
          <div className="d-flex justify-content-center bd-highlight">
            <div className="d-fliex currentOutages">
              <h4>Current Outages</h4>
              <div className="container">
                <div className="col-12">
                  <CurrentOutagesContainer services={this.props.services} />
                </div>
              </div>
            </div>
          </div>
          <div className="d-flex align-items-center flex-column bd-highlight">
            <div className="d-fliex justify-content-center">
              <h4>Future Outages</h4>
              <div className="container" id="futureOutages">
                <div className="col-12">
                  <FutureOutagesContainer
                    futureOutages={this.props.futureOutages} services={this.props.services}
                  />
                </div>
              </div>

              <h4>Recurring Outages</h4>
              <div className="container" id="recurringOutages">
                <div className="col-12">
                  <RecurringOutagesContainer
                    recurringOutages={this.props.recurringOutages}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

const mapStateToProps = state => {
  console.log(state)
  return {
    futureOutages: state.futureOutages.futureOutages,
    recurringOutages: state.recurringOutages.recurringOutages, 
    services: state.services.services
  }
};


const mapDispatchToProps = dispatch => {
  return {
    getFutureOutages: () => dispatch(getFutureOutages()),
    getRecurringOutages: () => dispatch(getRecurringOutages()),
    getServices: () => dispatch(getServices())
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Dashboard); // this connects Dashboard to store

Контейнер:

import React from "react";
import FutureOutagesComponent from "../components/FutureOutagesComponent"

const FutureOutagesContainer = props => {

   return (
    <div>
         {props.futureOutages && props.futureOutages.map((futureOutage, idx) => (
           <FutureOutagesComponent key={idx} futureOutage={futureOutage} services={props.services} />
         ))
         }
    </div>
  )

};

export default FutureOutagesContainer;

Компонент:

import React, { Component } from 'react';
import EditOutageModal from './EditOutageModal';
class FutureOutagesComponent extends Component {

   render() {

        return (
          <div>
            <div
              className="card text-white bg-info mb-3"
              style={{ maxWidth: "18rem" }}
            >
              <div className="card-body">
                <p className="card-text">
                  Service: {this.props.futureOutage.service.service}
                </p>
                <p className="card-text">
                  Start Time: {this.props.futureOutage.start_time}
                </p>
                <p className="card-text">
                  End Time: {this.props.futureOutage.end_time}
                </p>
                <p className="card-text">
                  Reason: {this.props.futureOutage.reason}
                </p>
              </div>

              <EditOutageModal
                outage={this.props.futureOutage}
                type="FO"
                services={this.props.services}
              />
            </div>
          </div>
        );
    }
}



export default FutureOutagesComponent; 

<EditOutageModal />, очевидно, где редактирование происходит. Я хочу, чтобы карта немедленно отражала обновление.

1 Ответ

0 голосов
/ 28 января 2020

Попробуйте

ComponentdidUpdate(prevProps) {
   const { getFutureOutages } this.props;

   if(getFutureOutages !== prevProps.getFutureOutages) {
      //to do
   }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...