繁体   English   中英

在由componentDidMount创建的React thats中切换崩溃

[英]Toggling collapse in React thats being created by componentDidMount

我正在调用一个API并将结果映射到我的状态,并且我也创建了一个可折叠的div,但是切换不起作用。 我正在使用div的react-bootstrap,它正在true和false之间更新状态的精细状态,但它不会影响崩溃。

async componentDidMount() {
  const response = await fetch('/api/getall');
  await response.json().then(data => {
  let results = data.data.map(item => {
      return(
        <div>
          <Button onClick={this.toggleOpen.bind(this)}>+</Button>
          <Panel expanded={this.state.open}>
            <Panel.Collapse>
              <Panel.Body>
                {item.text}
              </Panel.Body>
            </Panel.Collapse>
          </Panel>
            <hr/>
        </div>
      )
    })
    this.setState({results: results});
  })
}

toggleOpen() {
  this.setState({ open: !this.state.open })
  console.log(this.state.open)
}

因此,将有多个可折叠的div返回并渲染到组件上,但是<Panel expanded={this.state.open}>似乎没有更新。 仅当我在渲染功能上移动面板时才有效

编辑:整个文件

import React, { Component } from "react";
import {Row, Col, Button, Panel} from 'react-bootstrap';

class Test extends Component {
  constructor(props) {
    super(props);
    this.state = {
      results: [],
      open: false
    }
  }

async componentDidMount() {
  const response = await fetch('/api/getall');
  const data = await response.json();
  this.setState({ results: data });
}

toggleOpen() {
  this.setState({ open: !this.state.open })
}
  render() {
    const { results } = this.state;
    console.log(results)
    return (
      <div>
        {results.map(item => {
          return(
            <div>
              <Button onClick={this.toggleOpen.bind(this)}>+</Button>
              <Panel expanded={this.state.open}>
                <Panel.Collapse>
                  <Panel.Body>
                    <p>ffff</p>
                  </Panel.Body>
                </Panel.Collapse>
              </Panel>
              <hr/>
            </div>
          )
        })}
      </div>
    );
  }
}

export default Test;

console.log(results)在页面加载时运行3次,并显示:

[]
{data: Array(2)}
{data: Array(2)}

但是如果我这样做{this.state.results.data.map(item => {结果显示为空数组

您不应该将组件保存到状态。 如您所知,这样做可能会导致状态更改和道具更改被忽略而不渲染。 只需将数据保存到状态,然后在render方法中创建组件。

async componentDidMount() {
  const response = await fetch('/api/getall');
  const data = await response.json();
  this.setState({ results: data });
}

render() {
  const { results } = this.state;
  return (
    <div>
      {results.map(item => {
        return(
          <div>
            <Button onClick={this.toggleOpen.bind(this)}>+</Button>
            <Panel expanded={this.state.open}>
              <Panel.Collapse>
                <Panel.Body>
                  {item.text}
                </Panel.Body>
              </Panel.Collapse>
            </Panel>
            <hr/>
          </div>
        )
      })}
    </div>

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM