gpt4 book ai didi

javascript - 如何将 React 中的状态从一个类传递到另一个类?

转载 作者:行者123 更新时间:2023-11-29 10:08:22 26 4
gpt4 key购买 nike

我正在使用 ES6 类通过 React 构建一个网络应用程序。我有一个将数据添加到数据库的 IndexPage.js 文件和 AdminLandingPage.js 文件,该文件在其 componentDidMount() 函数中读回数据库中当前的所有数据。

现在基本上两者都是分开工作的。我希望能够将数据保存在 IndexPage 中的状态(数组)中,然后将该状态传递给另一个文件,我可以在其中检查数组中是否有数据并设置表的状态(从而允许我不必刷新页面)。

IndexPage 在它的构造函数中有这个:

constructor(props) {
super(props);

this.state = {newbugs: []};
}

这里我将数据添加到数据库并设置 newbugs 数组的状态:

addBug = (newBug) => {
BugsApi.addBugData(newBug, data => {
this.setState({newbugs: data})
})
}

在我的 AdminLandingPage 构造函数中,我有:

constructor(props) {
super(props);

this.state = {bugs: []};
}

我正在读取数据库中当前所有数据的 componentDidMount() 函数:

componentDidMount() {

BugsApi.getBugData(data => {
this.setState({bugs: data})
})
}

^ 这是我想从我的 IndexPage 传递 newbugs 状态数组的地方,检查它是否有数据,然后更新此类中的 bugs 状态数组。

如果我可以更清楚地回答我的问题,请告诉我。我现在已经被困了几个小时。谢谢!

最佳答案

state 应该作为 props 在组件之间传递。例如:

class IndexPage extends React.Component {
constructor(props) {
super(props);
this.state = {newbugs: []};
}

...

render() {
return (
<AdminLandingPage bugs={this.state.newBugs}/>
)
}
}

class AdminLandingPage extends React.Component {

...

componentDidMount() {
// `newBugs`constant holds the bugs passed down from IndexPage
const newBugs = this.props.bugs;
BugsApi.getBugData(data => {
this.setState({bugs: data})
})
}

...
}

这里 IndexPagestate.newBugs 传递给它的子组件 AdminIndexPage 作为 bugs 属性

关于javascript - 如何将 React 中的状态从一个类传递到另一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38601580/

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