2016-09-22 43 views
0

我想將我從API獲得的數據發送到REACT中的另一個組件,我應該怎麼做?我嘗試了「道具」,但我仍然是一個新手,並沒有得到如何將數據傳遞給另一個組件,正如你可以在<h2> John Doe </ h2>的「user.jsx」代碼中看到的那樣,我想要打印數據來自API 「usuario」,任何建議,請重新使用來自API的數據React

api.jsx

import React from 'react' 
import MenuProfile from './user.jsx' 


export default class Cliente extends React.Component { 
    constructor() { 
     super() 
     this.state = { clientId: '', usuario: '' } 
    } 
    componentWillMount() { 
     fetch('MYURL', { 
     method: 'POST', 
     body: JSON.stringify({ 
      usuario: 'test', 
      password: 'test', 
     }) 

     }) 
     .then((response) => { 
     return response.json() 
     }) 
     .then((data) => { 
     this.setState({ clientId: data.clientId, usuario: data.usuario }) 
     }) 
    } 
    render() { 
     return (
      // Testing if the state prints with success 
      <div className="container-fluid"> 
      <div>{this.state.usuario}</div> <---- this data (name) 
      </div> 
     ); 
     } 
} 

user.jsx

import React from 'react'; 
import Cliente from './api.jsx' 

export default class MenuProfile extends React.Component { 
    render() { 
    console.log(); 
    return (
     <div className="profile"> 
     <div className="profile_pic"> 
      <img src="../assets/images/img.jpg" alt="..." className="img-circle profile_img"></img> 
     </div> 
     <div className="profile_info"> 
      <span>Welcome,</span> 
      <h2>Jhon Doe</h2> <---- insert here (from api.jsx) 
     </div> 
     </div> 
     ); 
    } 
} 
+0

有與進行API調用,存儲數據,再利用數據等我創造了很多的樣板lib將其抽象出來。看看它對你有用! https://github.com/DigitalGlobe/jetset – glortho

回答

0

爲此,您需要致電MenuProfile根據Cliente

進口從「反應」 進口MenuProfile陣營從「./user.jsx」

export default class Cliente extends React.Component { 
    constructor() { 
     super() 
     this.state = { clientId: '', usuario: '' } 
    } 
    componentWillMount() { 
     fetch('MYURL', { 
     method: 'POST', 
     body: JSON.stringify({ 
      usuario: 'test', 
      password: 'test', 
     }) 

     }) 
     .then((response) => { 
     return response.json() 
     }) 
     .then((data) => { 
     this.setState({ clientId: data.clientId, usuario: data.usuario }) 
     }) 
    } 
    render() { 
     return (
      // Testing if the state prints with success 
      <div className="container-fluid"> 
      <div>{this.state.usuario}</div> <---- this data (name) 
      <MenuProfile name={this.state.usuario} /> 
      </div> 
     ); 
     } 
} 


import React from 'react'; 
import Cliente from './api.jsx' 

export default class MenuProfile extends React.Component { 
    render() { 
    cont {name} = this.props 
    console.log(); 
    return (
     <div className="profile"> 
     <div className="profile_pic"> 
      <img src="../assets/images/img.jpg" alt="..." className="img-circle profile_img"></img> 
     </div> 
     <div className="profile_info"> 
      <span>Welcome,</span> 
      <h2>{name}</h2> <---- insert here (from api.jsx) 
     </div> 
     </div> 
     ); 
    } 
} 
相關問題