gpt4 book ai didi

javascript - 如何在不导入组件ReactJS的情况下传递状态?

转载 作者:行者123 更新时间:2023-11-28 17:32:04 24 4
gpt4 key购买 nike

我有一个程序,通过 Body.js 的函数,有两个不同的路由(Body.jsUser.js),我保存state 中名为 employeeCurrent 的值,我想在 User.js 路由上使用此 employeeCurrent

我想知道如何做到这一点,而无需将 User.js 导入到 Body.js 中,因为 User.js > 将与 Body.js 一起出现。

My Body.js 的功能:

import React from "react";
import "./Body.css";
import axios from "axios";
import { Link } from "react-router-dom";

class Body extends React.Component {
constructor() {
super();

this.state = {
employee: [],
employeeCurrent: []
};
}

componentDidMount() {
axios
.get("http://127.0.0.1:3004/employee")
.then(response => this.setState({ employee: response.data }));
}

getName = () => {
const { employee } = this.state;
return employee.map(name => (
<Link className="link" to={`/user/${name.name}`}>
{" "}
<div onClick={() => this.add(name)} key={name.id} className="item">
{" "}
<img
className="img"
src={`https://picsum.photos/${name.name}`}
/>{" "}
<h1 className="name"> {name.name} </h1>
</div>{" "}
</Link>
));
};

add = name => {
const nam = name;
this.state.employeeCurrent.push(nam);
console.log(this.state.employeeCurrent);
};

render() {
return <div className="body">{this.getName()}</div>;
}
}

export default Body;

我的User.js:

import React from 'react';
import Body from './Body';


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

this.props = {
employeeCurrent: [],
}
}

有人可以帮助我吗?

最佳答案

您需要lift the state up:

Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor.

这正是您需要做的。 Home 应保留 employeeCurrent 并将其传递给 BodyUser

另一种方法是使用状态管理库,如 redux 或 mobx。

关于javascript - 如何在不导入组件ReactJS的情况下传递状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50087631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com