【发布时间】:2019-07-27 03:46:20
【问题描述】:
我想通过 axios 调用服务器后端来更新他们的投票数。
一切正常。
这是来自 axios 调用的 json 响应示例。
[{ "id": "1", "name": "contestant 1", "vote": "300" }]
我的问题:
我唯一的问题是加载事件。当我点击第一个参赛者通过 axios 调用更新其投票结果时。反而 应用程序显示Content Loading... 仅针对点击参赛者按钮,它会显示Content Loading... 为所有三个参赛者按钮。
我想要什么:
请问我如何只为点击的参赛者按钮显示 Content Loading...
我猜这与被点击的参赛者的 ID 有关。这个我也试过了,没办法
if (person.id === person_id){
this.setState({ loading: true });
}
这是代码
import React, { Component, Fragment } from "react";
import { render } from "react-dom";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
loading: false,
isLoading: true
};
}
componentDidMount() {
this.setState({
data: [
{ id: "1", name: "contestant 1", vote: "3" },
{ id: "2", name: "contestant 2", vote: "6" },
{ id: "3", name: "contestant 3", vote: "2" }
]
});
}
handleVote(person_id, person_vote) {
const data_vote = {
person_id: person_id,
person_vote: person_vote
};
this.setState({ loading: true }, () => {
axios.get("http://localhost/apidb_react/result.json", { data_vote })
.then(response => {
const newData = this.state.data.map(person => {
if (person.id !== person_id) return person;
return { ...person,vote: response.data[0].vote };
});
this.setState(state => ({
data: newData,
loading: false,
}));
})
.catch(error => {
console.log(error);
});
});// close loading
}
render() {
let data_loading;
if (this.state.loading) {
data_loading = "Content Loading......"
}
return (
<span>
<label>
<ul>
{this.state.data.map(person => (
<li key={person.id}>
{person.name} --(vote count: {person.vote})
<br />
{data_loading}
<button
type="button"
onClick={() => this.handleVote(person.id, person.vote)}
> Get Vote</button>
</li>
))}
</ul>
</label>
</span>
);
}
}
【问题讨论】:
-
将数据更改为
{ id: "1", name: "contestant 1", vote: "3", isLoading: false },,然后更改为{person.isLoading && "Content Loading.."},而不是{data_loading}。你明白了吗? -
@FortyTwo 这个概念行不通。没有显示任何结果。没有错误信息
标签: reactjs