在React中的同级组件之间传输数据

时间:2019-02-12 05:20:52

标签: javascript reactjs

我需要将API调用中获得的数据从一个同级组件传输到另一个同级组件。数据已成功从child1(NameForm)传输到父项(App)(由console.log确认)。但是,当我将道具从父项传递到child2(配置文件)时,它不存在。

我猜测问题出在异步。那么,如何使父项仅在收到数据后才将道具传递给child2,或者如何使child2在收到未定义的道具后再次渲染?

App.js

import React, { Component } from 'react';
import NameForm from './NameForm.js';
import Profile from './Profile.js'
import './App.css';

class App extends Component {
   constructor(props){
   super(props);
   this.state = {
      response: ''
   };
   this.getResponse = this.getResponse.bind(this)
}

 getResponse(res) {
     this.setState({
        response: res.data
     }, () => {
     console.log(this.state.response)
    })
  }

  render() {
     return (
       <div>
          <NameForm onGettingData={this.getResponse}/>
          <Profile res={this.state.responses}/>
       </div>
    );
  }
}

export default App;

NameForm.js

import React from 'react';
import axios from 'axios';

class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {
  value: '',
  response: ''
};

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
 }

handleChange(event) {
this.setState({value: event.target.value});
}

 handleSubmit(event) {
// alert('A name was submitted: ' + this.state.value);
axios.get(`/user?username=${this.state.value}`)
.then((res) => {
  this.props.onGettingData(res)
})
.catch((error)=> {
  console.log(error)
})
event.preventDefault();
}

render() {
return (
  <form onSubmit={this.handleSubmit}>
    <label>
      u/
      <input type="text" value={this.state.value} onChange={this.handleChange} />
    </label>
    <input type="submit" value="Submit" />
  </form>
);
  }
 }

export default NameForm;

Profile.js

import React from 'react';

class Profile extends React.Component {
  constructor(props) {
super(props);
  }

 render() {
if (this.props.res) {
  return(
    <div>{this.props.res.map(item => <li key={item.id}>{item.subreddit}</li>)}</div>
  )
} else {
  return null
  }
 }
}

export default Profile;

1 个答案:

答案 0 :(得分:0)

我认为您在App.js中有错字,<Profile res={this.state.responses}/>。 在这种状态下,您写了response,而您正在传承responses