如何显示点击时的当前状态

时间:2019-01-27 11:11:33

标签: javascript reactjs

如何显示当前更新状态。

我具有onClick功能<span onClick={() => { this.toggleCollapse(i, info) }}><img src={Arrow_Down} alt='Arrow' /></span>来切换卡。 但是我有一个问题,因为再次点击该卡就将其打开。 第一次单击我的状态showCards: []为空。

我想在状态下更新此数组

{title: "title3", description: "Sed non urna. Donec et ante. Phasellus eu ligula. … dolor at aliquet laoreet, mauris turpis porttito", open: "inactive"}description: "Donec et ante. Phasellus eu ligula. Vestibulum sit amet purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttito"open: "inactive"title: "title3"__proto__: Object iiiii 6

但最后一个对象open(如果处于活动状态则变为非活动状态)。

我具有该功能,但不能很好地工作。

这里是我的组成部分

import React, { Component } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import Header from '../../common/Header/'
import Masonry from '../../common/Masonry/'
import { cardAction } from '../../store/actions/Cards'
import Arrow_Down from '../../assets/img/arrow-down.svg'

class Dashboard extends Component {

  componentDidMount() {
    this.props.cardAction()
  }
  constructor(props) {
    super(props)
    this.state = {
      collapsed: true,
      class: 'collapsed',
      showCards: []
    }
    this.toggleCollapse = this.toggleCollapse.bind(this);
  }

  toggleCollapse(i, info) {
    console.log('i', info, 'iiiii', i)
    this.setState({
      collapsed: !this.state.collapsed,
      class: this.state.collapsed ? '' : 'collapsed',
      showCards: info
    });
    // this.setState(prevState => {
    //   return { showCards: !prevState.info };
    // });
    if (this.state.showCards.open === 'active') {
      this.state.showCards['open'] = 'inactive'
      console.log('open')
    }
    else {
      this.state.showCards['open'] = 'active'
      console.log('close')
    }
    console.log('showwww', this.state.showCards)
  }

  render() {
    const cardList = this.props.Cards.map((info, i) => {
      return (
        <div className={(info.open === 'active') ? 'collapsed' : ''} key={i}>
          <div className={(info.open === 'active') ? 'header flex space-between active' : 'header flex space-between'}>
            <h2>{info.title}</h2>
            <span onClick={() => { this.toggleCollapse(i, info) }}><img src={Arrow_Down} alt='Arrow' /></span>
          </div>
          <div className='content'>
            <p>{info.description}</p>
          </div>
        </div>
      )
    })
    return (
      <div>
        <Header />
        <Masonry columns={3} gap={20}>
          {cardList}
        </Masonry>
      </div>
    )
  }
}

Dashboard.defaultProps = {
  columns: 2,
  gap: 20,
  Cards: []
}
Dashboard.propTypes = {
  Cards: PropTypes.array.isRequired,
}

const mapStateToProps = state => {
  return { Cards: state.cards.result }
}

const mapDispatchToProps = dispatch => ({
  cardAction: () => dispatch(cardAction())
})
export default connect(mapStateToProps, mapDispatchToProps)(Dashboard)

编辑:

import React, { Component } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import Header from '../../common/Header/'
import Masonry from '../../common/Masonry/'
import { cardAction } from '../../store/actions/Cards'
import Arrow_Down from '../../assets/img/arrow-down.svg'

class Dashboard extends Component {

  componentDidMount() {
    this.props.cardAction()
  }
  constructor(props) {
    super(props)
    this.state = {
      collapsed: true,
      class: 'collapsed',
      showCards: []
    }
    this.toggleCollapse = this.toggleCollapse.bind(this);
  }

  toggleCollapse(i, info) {
    console.log('i', info, 'iiiii', i)
    this.setState({
      ollapsed: !this.state.collapsed,
      class: this.state.collapsed ? '' : 'collapsed',
      showCards: info
    }, () => {
      // my state is updated here !
      console.log('llllll', this.state.showCards.open)
      if (this.state.showCards.open === 'active') {
        console.log('open')
        this.setState({
          showCards: {
            open: 'inactive',
            ...this.state.showCards
          }
        })
      }
      else if (this.state.showCards.open === 'inactive') {
        this.setState({
          showCards: {
            open: 'active',
            ...this.state.showCards
          }
        })
      }
      // console.log('this state', this.state)
    })
  }

  render() {
    const cardList = this.props.Cards.map((info, i) => {
      return (
        <div className={(info.open === 'active') ? 'collapsed' : ''} key={i}>
          <div className={(info.open === 'active') ? 'header flex space-between active' : 'header flex space-between'}>
            <h2>{info.title}</h2>
            <span onClick={() => { this.toggleCollapse(i, info) }}><img src={Arrow_Down} alt='Arrow' /></span>
          </div>
          <div className='content'>
            <p>{info.description}</p>
          </div>
        </div>
      )
    })
    return (
      <div>
        <Header />
        <Masonry columns={3} gap={20}>
          {cardList}
        </Masonry>
      </div>
    )
  }
}

Dashboard.defaultProps = {
  columns: 2,
  gap: 20,
  Cards: []
}
Dashboard.propTypes = {
  Cards: PropTypes.array.isRequired,
}

const mapStateToProps = state => {
  return { Cards: state.cards.result }
}

const mapDispatchToProps = dispatch => ({
  cardAction: () => dispatch(cardAction())
})
export default connect(mapStateToProps, mapDispatchToProps)(Dashboard)

1 个答案:

答案 0 :(得分:1)

首先要了解的是setState是异步的(请参见React.Component#setState)。这意味着调用setState后,组件的状态不会立即更新。

但是setState接受一个回调函数,您可以在其中放置需要更新状态的代码。

this.setState({ ... }, () => {
    // my state is updated here !
});

Amir Saleem指出,不使用setState更新状态不是正确的方法。

this.state.showCards['open'] = 'active'

应该是

this.setState({
    showCards: {
        open: 'active',
        ...this.state.showCards
    }
});