反应 - 设置状态

时间:2017-01-15 06:59:13

标签: javascript json node.js reactjs axios

我正在关注Samer Buna的Lynda课程"全栈JavaScript开发:MongoDB,Node和React,"并且我想知道"命名竞赛的应用程序组件中的一段代码"应用。我的问题是关于前端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是&#39; api&#39;中唯一的文件。目录,它包括一个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"
    }
  ]
}

我以前见过传播运算符,但我不确定它是如何在这种情况下使用的。此外,&#39; [contest.id]:比赛&#39;我也很困惑。如果有人能提供一些澄清,我们将不胜感激!

1 个答案:

答案 0 :(得分:2)

因此,扩展运算符会将一个对象的所有键和值复制到另一个对象中。对于Redux reducer,它通常用于克隆状态并使存储不可变。

[contest.id]: contest正在计算密钥。请参阅Computed property keys

例如,给定contest.id34state.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
}