2016-07-26 108 views
2

我正在用React使用ES6类构建一个Web应用程序。我有一个IndexPage.js文件,它将数据添加到数据库和AdminLandingPage.js文件中,该文件读取当前位于componentDidMount()函数中的数据库中的所有数据。如何将React中的状态从一个类传递到另一个类?

现在基本上都是单独工作。我希望能够将数据保存在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()函数,我正在读取所有数据curre ntly数据库:

componentDidMount() { 

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

^这是我想从我的IndexPage检查newbugs状态数组中传递,如果它有它的数据,然后更新这个类的错误状态数组。

让我知道,如果我可以更清楚我的问题。现在我已经坚持了几个小时。谢谢!

+1

你应该阅读文档,这是等反应101的东西在这里我只是用Google搜索词的确切的疑问词,并得到这个:https://facebook.github.io/react/tips/communicate-between-这个例子中的components.html – JordanHendrix

回答

3

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}) 
    }) 
    } 

    ... 
} 

这里IndexPage通过state.newBugs到它的子组件AdminIndexPage作为bugs道具

+0

你正在传递状态。我通常同意你的说法,但第一句话是误导性的。 'State should be passed between components as props'will be cleararer – JordanHendrix

+1

你说得对,我会编辑答案 –

+0

唯一的问题是我不想渲染管理页面里面的索引页。如果我要把' '你有它的地方,它会渲染整个组件。 – Dan

0

我大多与通过红色水银提供的代码一致,与那里面设置的状态异常你的AdminLandingPage。一旦道具在组件内部可用,您将不需要AdminLandingPage组件中的状态,除非您尝试做的事情没有提及。

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

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

const AdminLandingPage = (props) { 
    console.log(props.bugs); 
    return (
    ... 
); 
} 
+0

有没有什么办法可以做到这一点,而不呈现管理页面里面的indexpage?我只想传递道具但不渲染组件。 – Dan

+0

做到这一点的最佳方式(具有很大的学习曲线,取决于您对React的适应程度)是Redux。 Redux是管理React App应用程序状态的好方法。 – Matt

相关问题