我正在调用API并将结果映射到我的状态,我也创建了一个可折叠的div,但是切换不起作用。我正在使用react-bootstrap作为div,它正在更新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}>
似乎没有得到更新。它只适用于我在渲染功能上移动Panel
编辑:整个文件
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>
}