在由componentDidMount

时间:2018-08-29 17:23:06

标签: javascript reactjs

我正在调用一个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(结果)在页面加载时运行3次并显示:

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

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

1 个答案:

答案 0 :(得分:2)

您不应将组件保存到状态。如您所知,这样做可能会导致状态更改和道具更改被忽略而不渲染。只需将数据保存到状态,然后在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>

}