0
私はReactとReduxには本当に新しいです。私はにconsole.logを行うときに、私は、サーバーから必要なこと応答を見ない私はresponse.jsonからデータを取得してコンポーネントに渡すにはどうすればいいですか?
// 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(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())))
}
私のPOSTメソッドです。
しかし、私はその応答をどのように取るか/現在の状態として変数/ストアに格納しているので、画面に表示するためにそれをロケーションコンポーネントに渡すことはできません。結果は次のように表示されます。
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}__proto__: Promise[[PromiseStatus]]: "resolved"[[PromiseValue]]: Objecthospitals: (3) [{…}, {…}, {…}]pharmacies: (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]restaurants: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]schools: (20)[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]trains: (2) [{…}, {…}]__proto__: Object
ありがとうございます。
ありがとうございます、あなたは私を正しい方向に押し込んでくれました。 –