反应 - 设置状态

React - setting state

我正在关注 Samer Buna 关于 "Full-Stack JavaScript Development: MongoDB, Node and React," 的 Lynda 课程,我想知道 "Naming Contests" 应用程序的 App 组件中的一段代码。我的问题是关于前端 React App 组件,特别是设置状态。我无法弄清楚的代码块是:

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]: 比赛'也让我感到困惑。如果有人能提供一些说明,我们将不胜感激!

因此展开运算符会将一个对象的所有键和值复制到另一个对象中。在 Redux reducer 的情况下,这通常用于克隆状态并保持存储不可变。

[contest.id]: contest 正在计算一个密钥。参见 Computed property keys

例如,给定 contest.id34,并且 state.constests 包含比赛 32 和 33,您最终会得到一个如下所示的对象:

{
  '32': {}, // This is the same value as it was in the initial store
  '33': {}, // ... same here
  '34': contest // That's the new contest you want to inject in the store
}