我正在向服务器发送一个有关我拥有的每个名称的http请求。该名称将作为请求参数发送,并返回特定于该名称的数据,但是,返回的数据不会与关联的名称一起返回。我正在尝试用数据创建表,但无法将名称链接到返回的数据。
class Campaigns extends Component {
state = {
campaigns: [
{
name: 'intelligent dentistry - oklahoma city'
},
{
name: 'intelligent dentistry - cincinnati'
},
{
name: 'intelligent dentistry - sanford'
},
{
name: 'intelligent dentistry - louisville'
},
{
name: 'intelligent dentistry - austin'
}
],
campaignData: []
}
componentDidMount(){
let campArray = []
this.state.campaigns.forEach((campaign, i) => {
let encodedName = encodeURIComponent(campaign.name.trim())
axios.get(`/api/campaign/${encodedName}`).then((res) => {
console.log(res.data.data)
campArray.push(res.data.data)
this.setState({
campaignData: [...campArray]
})
})
})
}
render() {
console.log(this.state.campaignData)
let campaignTableData = this.state.campaignData.map((campaign, i) => (
<>
<tr>
<td>Name</td>
<td>{campaign.totals.visits}</td>
<td>{campaign.totals.contacts ? campaign.totals.contacts : '0'}</td>
<td>{campaign.totals.customers ? campaign.totals.customers : '0'}</td>
</tr>
</>
))
返回的数据-
totals:
bounceRate: 1
bounces: 2
pageviewsPerSession: 1
rawViews: 2
visits: 2
我击中的终点-
app.get('/api/campaign/:campaign', (req, res) => {
console.log(req.params)
axios.get(`https://api.hubapi.com/analytics/v2/reports/utm-campaigns/total?hapikey=test&d1=${req.params.campaign}`).then((response) => {
let json = CircularJSON.stringify(response)
res.status(200).send(json)
}).catch((err) => {
console.log(err)
})
})
答案 0 :(得分:0)
设置状态时,您可以自己加上名称,因为您已经知道它了。代码的另一个问题是您当前正在对每个请求覆盖state.campaignData而不是添加到请求上。您还需要在campaignData的先前状态下进行合并。
this.setState(previousState => ({
campaignData: [ ...previousState.campaignData, { ...campArray, name: campaign.name }]
}));
...
<td>{campaign.name}</td>
<td>{campaign.totals.visits}</td>