ReactJs从选择列表更新状态

时间:2018-10-19 14:11:25

标签: reactjs

我有一个react-select组件和一个axios GET中的选项,我希望我的Car组件在选择该选项时显示来自组件状态下存储的URL的图像。 / p>

我正在使用componentDidMountcomponentDidUpdate,但是在componentDidUpdate中,this.getImage(capID);不断触发,如何防止这种情况发生并引发一次?

import React from "react";
import axios from "axios";
import { Panel } from "react-bootstrap";

export default class CarList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      imageSrc: ""
    };

    this.getImage = this.getImage.bind(this);
  }
  getImage(id) {
    axios
      .get(`xxx${id}`)
      .then(response => {
        this.setState({
          imageSrc: response.data.url
        });
      })
      .catch(error => {
        console.log(error);
      });
  }

  componentDidMount() {
    const {
      agrNo,
      balloon,
      bpid,
      capID,
      dealer,
      derivative,
      id,
      make,
      model,
      name
    } = this.props.car;

    this.getImage(capID);
  }
  componentDidUpdate() {
    const {
      agrNo,
      balloon,
      bpid,
      capID,
      dealer,
      derivative,
      id,
      make,
      model,
      name
    } = this.props.car;

    this.getImage(capID);
  }

  render() {
    let car = this.props.car;

    const {
      agrNo,
      balloon,
      bpid,
      capID,
      dealer,
      derivative,
      id,
      make,
      model,
      name
    } = this.props.car;



    return (
      <div className="car-details">
        <Panel header={name}>
          <div className="flex-container">
            <div className="flex-item">
              {this.state.imageSrc && (
                <img
                  src={this.state.imageSrc}
                  alt={model}
                  className="car-details__image"
                />
              )}
            </div>
            <div className="flex-item">
              <p>{car.Plot}</p>
              <div className="car-info">
                <div>
                  <span>Genre:</span> {car.Genre}
                </div>
              </div>
            </div>
          </div>
        </Panel>
      </div>
    );
  }
}

应用程序:

import React, { Component } from "react";
import logo from "./logo.svg";
import axios from "axios";
import { Alert } from "react-bootstrap";
import AsyncSelect from "react-select/lib/Async";
import CarList from "./CarList";
import "react-select/dist/react-select.css";
import "./App.css";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      car: {}
    };
  }

  getCars(e) {
    return axios
      .get(`xxx${e}`)
      .then(response => {
        var arr = [];
        if (response.data !== undefined) {
          var searchResults = response.data.length;
          for (var i = 0; i < searchResults; i++) {
            arr.push({
              label: `${response.data[i].name} - ${response.data[i].id}`,
              value: response.data[i].id
            });
          }
        }
        return {
          options: arr
        };
      })
      .catch(error => {
        console.log(error);
      });
  }

  getCar(e) {
    axios
      .get(`xxx}`)
      .then(response => {
        this.setState({
          car: response.data
        });
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    const {
      car: { id }
    } = this.state;
    return (
      <div className="container">
        <AsyncSelect
          name="carOwner"
          value="ABC"
          cacheOptions
          defaultOptions
          loadOptions={this.getCars}
          onChange={this.getCar.bind(this)}
        />

        {id ? (
          <CarList car={this.state.car} />
        ) : (
          <Alert bsStyle="info">
            <p>Enter a surname above to begin...</p>
          </Alert>
        )}
      </div>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:0)

只要此组件的任何道具或状态发生更改,就会触发

componentDidUpdate(请查看official docs以获取更多信息)。

您正在更改getImage(id)函数内部的状态,每次发生时,componentDidUpdate函数都会根据您的情况触发,这将再次调用getImage函数,然后将成为无限循环。

您需要检查capID道具是否已更改,以确定是否应该再次拨打电话:

componentDidUpdate(oldProps) {
    const {
      agrNo,
      balloon,
      bpid,
      capID,
      dealer,
      derivative,
      id,
      make,
      model,
      name
    } = this.props.car;

    const oldCapID = oldProps.capID;

    if (capID !== oldCapID) {
      this.getImage(capID);
    }
}