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>
);
}
}
有与进行API调用,存储数据,再利用数据等我创造了很多的样板lib将其抽象出来。看看它对你有用! https://github.com/DigitalGlobe/jetset – glortho