组件,该组件从getConvForNum上的服务器获取数据,但以某种方式进入无限循环。 即使我只保留render()和此函数,它也会继续向服务器发送GET请求。
OpentTickets.js
P*P*P*P*P
App.js
import React from 'react';
import axios from 'axios';
import {Button, Accordion, Card, Form} from 'react-bootstrap';
export default class PersonList extends React.Component {
state = {
people: [],
customer_pn: '',
date: '',
conversation: []
};
componentDidMount() {
axios.get(`/getongoing?limit=10`)
.then(res => {
const people = res.data;
this.setState({people});
});
}
getConvForNum(phone_nm) {
axios.get('/getconvfornum?customer_number=' + phone_nm.slice(1)).then(res => {
const conversation = res.data;
this.setState({conversation})
});
return (
this.state.conversation.map(message =>
<div>
<p>{message.from}</p>
<p>{message.body}</p>
</div>
)
)
}
render() {
return (
this.state.people.map(person =>
<>
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<Accordion.Toggle as={Button} variant="button" eventKey="0">
Converstaion random
</Accordion.Toggle>
Phone number: {person}
</Card.Header>
<Accordion.Collapse eventKey="0">
<Card.Body>
{this.getConvForNum(person)}
<Form.Control type = 'text'/>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
</>
)
)
}
}
不确定是什么原因导致了无限循环 我是新来的反应者,所以可能我只是不了解某些东西
答案 0 :(得分:1)
在render函数内部,您有一个getConvForNum(person)
调用,它将执行get请求并设置状态,
SetState
将触发渲染函数调用,渲染将再次调用getConvForNum(person)
,依此类推。
您可以在设置状态之前将this.state.conversation
与get调用的新返回值进行比较,以避免无限调用