我正在關注Samer Buna的Lynda課程「完全堆棧JavaScript開發:MongoDB,Node和React」,並且想知道「命名比賽」應用程序的App組件中的一段代碼。我的問題是關於前端React App組件,特別是設置狀態。我無法搞清楚碼塊是:React - 設置狀態
contests: {
...this.state.contests,
[contest.id]: contest
}
在App組分fetchContest()函數內部 - App.js:
import React from 'react';
import Header from './Header';
import ContestList from './ContestList';
import Contest from './Contest';
import * as api from '../api';
const pushState =(obj, url) =>
window.history.pushState(obj, '', url);
class App extends React.Component {
static propTypes = {
initialData: React.PropTypes.object.isRequired
};
state = this.props.initialData;
componentDidMount() {}
componentWillUnmount() {}
fetchContest = (contestId) => {
pushState(
{ currentContestId: contestId },
`/contest/${contestId}`
);
api.fetchContest(contestId).then(contest => {
this.setState({
currentContestId: contest.id,
contests: {
...this.state.contests,
[contest.id]: contest
}
});
});
// lookup the contest
// convert contests from array to object, for constant time lookup
// this.state.contests[contestId]
}
pageHeader() {
if (this.state.currentContestId) {
return this.currentContest().contestName;
}
return 'Naming Contests';
}
currentContest() {
return this.state.contests[this.state.currentContestId];
}
currentContent() {
if (this.state.currentContestId) {
return <Contest {...this.currentContest()} />;
}
return <ContestList
onContestClick={this.fetchContest}
contests={this.state.contests} />;
}
render() {
return (
<div className="App">
<Header message={this.pageHeader()} />
{this.currentContent()}
</div>
);
}
}
export default App;
api.js是內部的唯一的文件'API' 目錄中,並且它包括一個Axios公司呼叫以檢索對應於每個競賽JSON對象:
api.js:
import axios from 'axios';
export const fetchContest = (contestId) => {
return axios.get(`/api/contests/${contestId}`)
.then(resp => resp.data);
};
參考,爭奇鬥豔的JSON內容是這樣的:
{
"contests": [
{
"id": 1,
"categoryName": "Business/Company",
"contestName": "Cognitive Building Bricks"
},
{
"id": 2,
"categoryName": "Magazine/Newsletter",
"contestName": "Educating people about sustainable food production"
},
{
"id": 3,
"categoryName": "Software Component",
"contestName": "Big Data Analytics for Cash Circulation"
},
{
"id": 4,
"categoryName": "Website",
"contestName": "Free programming books"
}
]
}
我以前見過的傳播經營者,但我不確定它是如何在這種情況下究竟使用。此外,'[contest.id]:比賽'也令我困惑。如果有人可以提供一些澄清,將非常感謝!
我明白了 - 謝謝。我的一部分困惑是試圖理解他爲什麼要分配參加比賽。在整個比賽中,但身份證與比賽對象中的比賽位置相同(通過順序),[比賽比賽] =比賽只是將比賽對象更新爲新的比賽對象,因爲當在axios調用中檢索比賽時,我忘記了注意在api路由器中添加了比賽。描述,這是作爲比賽組件的一部分的必需屬性。 –