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

问题描述 投票:5回答:2

需要帮助反应...尝试使用天气信息实现可折叠的卡片列表。已经实现了展开和折叠的行为,但是当我点击一个面板时,另一个面板同时打开(我有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;
javascript reactjs collapse expand
2个回答
4
投票

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

像这样:

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

...

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

...

切换功能就像这样使用,例如,第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>

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方法来绘制视图,divs get the sameBoolean`值的两个部分。因此,他们都崩溃了。

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

创建一个单独的组件,它有两个工作要做: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>
    )
} 

希望这能解决用例。

© www.soinside.com 2019 - 2024. All rights reserved.