如何从response.json获取数据并将其传递给组件?

时间:2017-08-29 18:57:26

标签: redux react-redux

我是React和Redux的新手。我创建了这个表单

// node modules
import React, { Component } from 'react';
import { Field, reduxForm, SubmissionError } from 'redux-form';

// custom modules
import apiRequest from '../../redux/modules/apiRequests';

const renderField = ({ type, label, input, meta: { touched, error }}) => (
    <div className="input-row">
      <br />
      <label>{label}</label>
      <br />
      <input {...input} type={ type }/>
      { touched && error &&
       <span className="error">{ error }</span>}
    </div>
  )

class LocationForm extends Component {
  constructor(props){
    super(props)

    this.state = {
      address: '',
      city: '',
      state: ''
    }
  }

  handleOnChange = event => {
   this.setState({
     [event.target.name]: event.target.value
   });
 }

  submit = ({ address='', city='', state=''}) => {
    // console.log(`state: ${this.state.address}`)
    let error = {};
    let isError = false;

    if (address.trim() === '') {
      error.address = 'Required';
      isError = true;
    }

    if (city.trim() === '') {
      error.city = 'Required';
      isError = true;
    }

    if (state.trim() === '') {
      error.state = 'Required';
      isError = true;
    }

    if (isError) {
      throw new SubmissionError(error);
    } else {
      console.log(this.props)
      apiRequest.post(`/search`, this.state)
      console.log(this.props)
      this.setState({ address: '', city: '', state: ''})
    }
  }

  render() {
    return (
      <form onSubmit={ this.props.handleSubmit(this.submit) }>
        <Field name="address" label='Address: ' component={renderField} type="text" onChange={this.handleOnChange} />
        <Field name="city" label='City: ' component={renderField} type="text" onChange={this.handleOnChange}/>
        <Field name="state" label='State: ' component={renderField} type="text" onChange={this.handleOnChange}/>
        <button type="submit">Submit</button>
      </form>
    )
  }
}

LocationForm = reduxForm({
  form: 'location'
})(LocationForm)

export default LocationForm;

这是apiRequest.js中的post方法

post(url, body) {
  return fetch(API_URL + url, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body)
  }).then(response => console.log((response.json())))
  }

当我执行console.log时,我确实看到了服务器所需的响应。

但我只是不明白如何将该响应/存储在变量/存储中作为当前状态,以便我可以将其传递给位置组件以在屏幕上显示它。我确实看到结果......

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}__proto__: Promise[[PromiseStatus]]: "resolved"[[PromiseValue]]: Objecthospitals: (3) [{…}, {…}, {…}]pharmacies: (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]restaurants: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]schools: (20)[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]trains: (2) [{…}, {…}]__proto__: Object

感谢您对此提出的任何建议。

1 个答案:

答案 0 :(得分:1)

response.json返回一个Promise。如果您对它们了解不多,我建议您查看Promise

您需要做的是返回response.json()的结果,然后从响应中读取数据。

post(url, body) {
  return fetch(API_URL + url, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body)
  }).then(response => (response.json())).then((json) => {
    console.log('Response JSON: ', json);
  })
}