我是个新手,正在为如何将数据从一个组件传输到另一个组件而苦苦挣扎。
我参考了一些教程和博客,但事情对我来说都不起作用。
我有两个子组件Body-content.jsx和Profile.jsx以及一个父组件parent.jsx
我想从Body-content.jsx向Profile.jsx传输一些数据。
这是我的代码
Body-content.jsx
class BodyContent extends React.Component {
componentDidMount() {
this.getUserList()
}
getUserList(){
fetch('https://jsonplaceholder.typicode.com/users')
.then(result => {
return result.json();
}).then(data =>{
this.setState({
users : data
})
})
}
render() {
const user = this.state.users.map((userData, i) => (
<CardBody>
...some code here
<Button color='primary' onClick={e => this.viewProfile(userData)}>View Profile</Button>
</CardBody>
</Card>
));
return (
<>
<div>{user}</div>
</>
)
}
viewProfile = function (data) {
}
}
export default BodyContent;profile.jsx
class Profile extends React.Component {
componentDidMount() {
}
render() {
return (
<>
<TopNav />
<main className="profile-page" ref="main">
<section>
//code goes here
</section>
</main>
</>
);
}
}
export default Profile;发布于 2019-11-18 18:21:41
嗨,欢迎来到React的世界
如果您想在同级组件之间共享数据,您应该始终记住,您应该将数据存储在最高公共组件(doc)中。
在您的情况下,这将意味着拥有一个父组件,该组件保存您的用户列表和处于其状态的当前配置文件,然后相应地呈现您的列表和当前配置文件。
让您走上“正轨”sandbox的一个小例子
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
users: [],
currentIndex: null
}
}
componentDidMount() {
this.getUserList()
}
getUserList(){
fetch('https://jsonplaceholder.typicode.com/users')
.then(result => result.json())
.then(data => {
this.setState(() => ({
users : data
}))
});
}
updateCurrent = (index) => {
this.setState(() => ({ currentIndex: index }));
}
render() {
return (
<div>
<UserList
users={this.state.users}
updateCurrent={this.updateCurrent}
/>
{this.state.currentIndex !== null && (
<Profile user={this.state.users[this.state.currentIndex]} />
)}
</div>
)
}
}
const UserList = (props) => (
<div>
{props.users.map((user, i) => (
<div key={user.id}>
<button color='primary' onClick={() => props.updateCurrent(i)}>View Profile</button>
</div>
))}
</div>
);
const Profile = ({ user }) => (
<div className="profile-page">
{user.name}
</div>
);如果需要,请随时要求澄清。
快乐的编码,
https://stackoverflow.com/questions/58911627
复制相似问题