无法从React Component中的获取功能设置状态

时间:2018-08-13 02:41:11

标签: javascript reactjs

我正在尝试通过提取函数设置状态,而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"));

任何建议将不胜感激。

1 个答案:

答案 0 :(得分:2)

.fa-bars{ content: "\f0c9"; font-family: FontAwesome; font-style: normal; font-weight: normal; } 不在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