反应扩大并崩溃只有一个面板

时间:2017-12-28 19:54:40

标签: javascript reactjs collapse expand

需要帮助才能做出反应...... 尝试使用天气信息实现可折叠的卡片列表。 已经实现了展开和折叠的行为,但是当我点击一个面板时,另一个面板同时打开(我有2个面板,需要7个来显示weahter一周7天)。

我如何只打开和关闭一个面板?

代码:

import React, { Component } from 'react';
import Moment from 'react-moment';

import RandomGif from './RandomGif.js';

const urlForCity = city => `https://cors-anywhere.herokuapp.com/http://api.openweathermap.org/data/2.5/forecast/daily?q=${city}&units=metric&cnt=7&appid=1fba7c3eaa869008374898c6a606fe3e`

class OpenWapi extends Component {
  constructor(props) {
    super(props);
    this.state = {
      requestFailed: false,
      shown: false
    }
    this.componentDidMount = this.componentDidMount.bind(this);
    this.toggle = this.toggle.bind(this);
  }

  componentDidMount() {
    fetch(urlForCity(this.props.city))
      .then(response => {
        if(!response.ok) {
          throw Error("Network request failed")
        }
        return response;
      })
      .then(data => data.json())
      .then(data => {
        this.setState({
          weatherData: data
        })
      }, () => {
        this.setState({
          requestFailed: true
        })
      })
  }

  toggle() {
        this.setState({
            shown: !this.state.shown
        });
    }

  render() {

    if(this.state.requestFailed) return <p>Request Failed.</p>;
    if(!this.state.weatherData) return <p>Loading...</p>;

    return (
      <div>
        <p>City: {this.state.weatherData.city.name}</p>

        {/* Day 1 */}
        <div onClick={this.toggle} className="dayWeekItem">
          <div className="top-content">
            <div className="icon-weather"></div>
            <div className="date">
              <div className="weekday">Today</div>
              <div className="day-long"><Moment unix format="MMM DD YYYY">{this.state.weatherData.list[0].dt}</Moment></div>
            </div>
            <div className="temperature">
              <div className="temp-high">{parseInt(this.state.weatherData.list[0].temp.max)}º</div>
              <div className="temp-low">{parseInt(this.state.weatherData.list[0].temp.min)}º</div>
            </div>
          </div>
          <div className={this.state.shown ? "toggleContent-open" : "toggleContent-closed"} >
            <div className="weather-gif" >
              <RandomGif keyword={this.state.weatherData.list[0].weather[0].description} />
            </div>
          </div>
        </div>



        {/* Day 2 */}
        <div onClick={this.toggle} className="dayWeekItem">
          <div className="top-content">
            <div className="icon-weather"></div>
            <div className="date">
              <div className="weekday">Tomorrow</div>
              <div className="day-long"><Moment unix format="MMM DD YYYY">{this.state.weatherData.list[1].dt}</Moment></div>
            </div>
            <div className="temperature">
              <div className="temp-high">{parseInt(this.state.weatherData.list[1].temp.max)}º</div>
              <div className="temp-low">{parseInt(this.state.weatherData.list[1].temp.min)}º</div>
            </div>
          </div>
          <div className={this.state.shown ? "toggleContent-open" : "toggleContent-closed"} >
            <div className="weather-gif" >
              <RandomGif keyword={this.state.weatherData.list[1].weather[0].description} />
            </div>
          </div>
        </div>

        {/* Day 3 */}


        {/* Day 4 */}


        {/* Day 5 */}


      </div>
    )
  }
}

export default OpenWapi;

2 个答案:

答案 0 :(得分:5)

它们都将随着您的实施而崩溃。

你有一个州

state = {
  shown: true
}

你有一个切换它的功能

toggle = () => {
   this.setState(shown: !this.state.shown)
}

您使用this.state.shown在两个位置渲染组件,但值始终为一truefalse

render() {
    return(<div .....//something>
        <div onClick={this.toggle}>
           { this.state.shown ? <SomeComponent or HTML Tag> : null }
        </div>
        <div onClick={this.toggle}>
          { this.state.shown ? <SomeComponent or HTML Tag> : null }
        </div>
    </div>)
}

所以无论你切换到哪里,一旦更新状态并再次调用render方法绘制视图,div s get the same布尔值的两个部分都值。因此,他们都崩溃了。

我可以为此问题提供的最佳解决方案是:

创建一个单独的组件,其中包含两个作业: 1.保持自己的崩溃状态truefalse。 2.渲染给它的孩子,而不用知道它们可能是什么。

所以说吧

 class WeatherWidget extends React.PureComponent {
   state= {
     shown: true
   }     
   toggle = () => this.setState({shown: !this.state.shown})
   render() {
       return(
         <div onClick={this.toggle} className="dayWeekItem">
            <div className="top-content">
            <div className="icon-weather"></div>
            <div className="date">
              <div className="weekday">Today</div>
              <div className="day-long">
                    <Moment unix format="MMM DD YYYY">{this.props.date}</Moment>
              </div>
            </div>
            <div className="temperature">
              <div className="temp-high">{parseInt(this.props.maxTemp)}º
              </div>
              <div className="temp-low">{parseInt(this.props.minTemp)}º
              </div>
            </div>
         </div>
             <div className={this.state.shown ? "toggleContent-open" : "toggleContent-closed"} >
                 <div className="weather-gif" >
                    <RandomGif keyword={this.props.gifDescription} />
                 </div>
              </div>
     </div>
       )
   }


 }

所以你创建了一个可重用的组件来管理它自己的状态(React Paradigm / Composition带来了可重用性)

至于显示多个小部件

class OpenWapi extends Component {
   constructor(props) {
      super(props);
      this.state = {
        requestFailed: false,
        shown: false
      }
      this.componentDidMount = this.componentDidMount.bind(this);
      this.toggle = this.toggle.bind(this);
    }

    componentDidMount() {
      fetch(urlForCity(this.props.city))
      .then(response => {
      if(!response.ok) {
         throw Error("Network request failed")
      }
      return response;
     })
     .then(data => data.json())
     .then(data => {
     this.setState({
        weatherData: data
       })
     }, () => {
       this.setState({
         requestFailed: true
     })
  })
}
render() {
    if(this.state.requestFailed) return <p>Request Failed.</p>;
    if(!this.state.weatherData) return <p>Loading...</p>;

    return(
    <div>
       <p>City: {this.state.weatherData.city.name}</p>
       <WeatherWidget 
          date={this.state.weatherData.list[0].dt}
          maxTemp={this.state.weatherData.list[0].temp.max}
          minTemp={this.state.weatherData.list[0].temp.min}
          gifDescription=
                {this.state.weatherData.list[0].weather[1].description}

       />
       <WeatherWidget 
          date={this.state.weatherData.list[1].dt}
          maxTemp={this.state.weatherData.list[1].temp.max}
          minTemp={this.state.weatherData.list[1].temp.min}
          gifDescription=
                {this.state.weatherData.list[1].weather[1].description}

       />
    </div>
    )
} 

希望这能解决用例。

答案 1 :(得分:4)

我会有一个对象来表示状态,每个面板都有一个字段。

像这样:

constructor(props) {
    ...
    this.state = {
      requestFailed: false,
      shown: {}
    }
    ...
}

...

toggle(panelNumber) {
   this.setState({
        shown: {
            ...this.state.shown,
            [panelNumber]: !this.state.shown[panelNumber]
        }
    });
}

...

toogle功能就像这样使用,例如第1天:

<div onClick={() => this.toggle(1)} className="dayWeekItem">
    ...
</div>

并以html显示,例如,第1天:

      <div className={this.state.shown[1] ? "toggleContent-open" : "toggleContent-closed"} >
        <div className="weather-gif" >
          <RandomGif keyword={this.state.weatherData.list[0].weather[0].description} />
        </div>
      </div>