gpt4 book ai didi

javascript - 无法从 React 组件中的 fetch 函数设置状态

转载 作者:行者123 更新时间:2023-12-01 01:47:58 24 4
gpt4 key购买 nike

我正在尝试从 fetch 函数设置状态,并且 api 似乎正确返回 json。但状态似乎从未填充来自 api 的数据。有人看到问题所在吗?该代码似乎运行良好并且没有显示任何错误,所以我不确定问题是什么。这是代码:

var count = 0;
const ActivityRow = props => (
<tr>
<td>{props.activity.Date.toString()}</td>
<td>{props.activity.ActivityType}</td>
<td>{props.activity.Value}</td>
</tr>
);

function ActivityTable(props) {
const ActivityRows = props.activities.map(activity => (
<ActivityRow key={activity.id} activity={activity} />
));
return (
<table className="bordered-table">
<thead>
<tr>
<th>Date</th>
<th>Activity Type</th>
<th>Value</th>
</tr>
</thead>
<tbody>{ActivityRows}</tbody>
</table>
);
}

function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? "pm" : "am";
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? "0" + minutes : minutes;
var strTime = hours + ":" + minutes + " " + ampm;
return (
date.getMonth() +
1 +
"/" +
date.getDate() +
"/" +
date.getFullYear() +
" " +
strTime
);
}

class ActivityAdd extends React.Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
var form = document.forms.ActivityAdd;
this.props.createActivity({
id: count++,
Date: formatDate(new Date()),
ActivityType: form.Activity.value,
Value: form.Value.value
});
// clear the form for the next input
form.Activity.value = "";
form.Value.value = "";
}
render() {
return (
<div>
<form name="ActivityAdd" onSubmit={this.handleSubmit}>
<input type="text" name="Activity" placeholder="Activity" />
<input type="text" name="Value" placeholder="Value" />
<button>Add</button>
</form>
</div>
);
}
}
class App extends React.Component {
constructor() {
super();
this.state = { activities: [] };
this.createActivity = this.createActivity.bind(this);
}

loadData() {
fetch("/api/activities")
.then(response => response.json())
.then(data => {
console.log("Total count of records:", data._metadata.total_count);
});
this.setState({ activities: data.records });
}
createActivity(newActivity) {
fetch("/api/activities", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newActivity)
})
.then(response => response.json())
.then(updatedActivity => {
const newActivities = this.state.activities.concat(newActivity);
this.setState({ activities: newActivities });
});
}
render() {
return (
<div>
<h1>Diabetes Self Management App</h1>
<hr />
<ActivityTable activities={this.state.activities} />
<hr />
<ActivityAdd createActivity={this.createActivity} />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("contents"));

如有任何建议,我们将不胜感激。

最佳答案

setState超出了data的范围,因此data未定义,导致设置状态失败。

loadData() {
fetch('/api/activities').then(response =>
response.json()
).then(data => {
console.log("Total count of records:", data._metadata.total_count);
});
// undefined here as data is not existed
this.setState({ activities: data.records });
}

解决方案是将 setState 移至 Promise 返回值内。

var count = 0;
const ActivityRow = props => (
<tr>
<td>{props.activity.Date.toString()}</td>
<td>{props.activity.ActivityType}</td>
<td>{props.activity.Value}</td>
</tr>
);

function ActivityTable(props) {
const ActivityRows = props.activities.map(activity => (
<ActivityRow key={activity.id} activity={activity} />
));
return (
<table className="bordered-table">
<thead>
<tr>
<th>Date</th>
<th>Activity Type</th>
<th>Value</th>
</tr>
</thead>
<tbody>{ActivityRows}</tbody>
</table>
);
}
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? "pm" : "am";
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? "0" + minutes : minutes;
var strTime = hours + ":" + minutes + " " + ampm;
return (
date.getMonth() +
1 +
"/" +
date.getDate() +
"/" +
date.getFullYear() +
" " +
strTime
);
}

class ActivityAdd extends React.Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
var form = document.forms.ActivityAdd;
this.props.createActivity({
id: count++,
Date: formatDate(new Date()),
ActivityType: form.Activity.value,
Value: form.Value.value
});
// clear the form for the next input
form.Activity.value = "";
form.Value.value = "";
}
render() {
return (
<div>
<form name="ActivityAdd" onSubmit={this.handleSubmit}>
<input type="text" name="Activity" placeholder="Activity" />
<input type="text" name="Value" placeholder="Value" />
<button>Add</button>
</form>
</div>
);
}
}
class App extends React.Component {
constructor() {
super();
this.state = { activities: [] };
this.createActivity = this.createActivity.bind(this);
}

loadData() {
fetch("/api/activities")
.then(response => response.json())
.then(data => {
console.log("Total count of records:", data._metadata.total_count);
// must be in this then scope
this.setState({ activities: data.records });
});

}
createActivity(newActivity) {
fetch("/api/activities", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newActivity)
})
.then(response => response.json())
.then(updatedActivity => {
const newActivities = this.state.activities.concat(newActivity);
this.setState({ activities: newActivities });
});
}
render() {
return (
<div>
<h1>Diabetes Self Management App</h1>
<hr />
<ActivityTable activities={this.state.activities} />
<hr />
<ActivityAdd createActivity={this.createActivity} />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("contents"));

关于javascript - 无法从 React 组件中的 fetch 函数设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51814550/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com