简体   繁体   English

在不同页面路由上的不同组件中反应状态

[英]React state in different component on different page route

I have been able to setState on a specific component called SubmitProject which lives at a specific route /submit . 我已经能够在名为SubmitProject的特定组件上设置setState,该组件位于特定的路由/submit Now I also have a route /portfolio that has a component called Portfolio I am wondering how do I get the state from SubmitProject to be the same on Portfolio Can you only share state with Components that are nested within each other. 现在,我也有一个路由/portfolio ,其中包含一个名为Portfolio的组件。我想知道如何从SubmitProject获得状态, SubmitProjectPortfolio上的状态相同。只能与彼此嵌套的组件共享状态。 What I am ultimately trying to do is use a form to submit text to state on the /submit route and then have that same state data update in the /portfolio route. 我最终想要做的是使用一种表单提交文本以在/submit路由上声明状态,然后在/portfolio路由中进行相同的状态数据更新。

I could be approaching the design wrong, Should everything maybe be in APP Component and I do the Routing different, I am very new to React, so I defintely need guidance on how to setup my project. 我可能会错误地进行设计,如果所有内容都可能在APP组件中,并且我做的路由不同,那么我对React还是很陌生,所以我绝对需要有关如何设置项目的指导。

Ok Thanks ahead of time. 好,谢谢。

Here is my relevant code 这是我的相关代码

src/components/SubmitProject.js

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

class SubmitProject extends React.Component {
    state = {
        sections:{}
    };
    addSection = section =>{
        const sections = {...this.state.sections};
        sections[`section${Date.now()}`] = section;
        this.setState({
            sections: sections
        });
    }
    render() {
        return(
            <React.Fragment>
                <h1>Submit Project</h1>
                <h2>Enter Project Data</h2>
                <PortfolioForm addSection={this.addSection} />
            </React.Fragment>
        )
    }
}

export default SubmitProject;

src/components/PortfolioForm.js

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

class Portfolio extends React.Component {
    render() {
        return(
            <React.Fragment>
                <h1>Submit Form</h1>
                <FormAdd addSection={this.props.addSection}/>
            </React.Fragment>
        )
    }
}

export default Portfolio;

src/components/FormAdd.js

import React from 'react';

class FormAdd extends React.Component {
    nameRef = React.createRef();

    createSection = (event) =>{
        event.preventDefault();
        const section = {
            name: this.nameRef.current.value
        };
        this.props.addSection(section);
    };  
    render() {
        return(
            <React.Fragment>
                <form onSubmit={this.createSection}>
                    <input type="text" ref={this.nameRef} name="name" placeholder="Name"/>
                    <button type="submit">+ Add Section</button>
                </form>
            </React.Fragment>
        )
    }
}

export default FormAdd;

src/components/Router.js

import React from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import Portfolio from './Portfolio';
import SubmitProject from './SubmitProject';
import App from './App';

const Router = () => (
    <BrowserRouter>
        <Switch>
            <Route exact path="/" component={App}/>
            <Route exact path="/portfolio" component={Portfolio}/>
            <Route exact path="/submit" component={SubmitProject}/>
        </Switch>
    </BrowserRouter>
);

export default Router;

src/Portfolio.js

import React from 'react';

class Portfolio extends React.Component {
    //CAN I GET STATE FROM SubmitProject.js FILE IN HERE?
    render() {
        return(
            <React.Fragment>
                <h1>Portfolio Page</h1>
                <h2>List of projects</h2>        
            </React.Fragment>
        )
    }
}

export default Portfolio;

If you're using React 16, then you could resolve this by using the Context API. 如果您使用的是React 16,则可以使用Context API来解决。 This would involve making the following adjustments to your code: 这将涉及对代码进行以下调整:

// PortfolioContext.jsx
// Define a PortfolioContext component with initial shared 'sections' state
export default const PortfolioContext = React.createContext(
  sections : {}
);

Then update your SubmitProject component to use the PortfolioContext component to update the shared sections state: 然后更新您的SubmitProject组件,以使用PortfolioContext组件更新共享sections状态:

// SubmitProject.jsx
// Use the ProtfolioContext component in your SubmitProject component to update
// the shared for use in the Portfolio component
import React from 'react';
import PortfolioForm from './PortfolioForm';
import PortfolioContext from './PortfolioContext';

class SubmitProject extends React.Component {
   constructor (props) {
        super(props)
        this.state = {
             sections:{}
        };
    }

    addSection = section =>{
        const sections = {...this.state.sections};
        sections[`section${Date.now()}`] = section;
        this.setState({
            sections: sections
        });
    }
    render() {
        return(
            { /* Inject the local sections state into provider */ }
            <PortfolioContext.Provider value={this.state.sections}>
                <React.Fragment>
                    <h1>Submit Project</h1>
                    <h2>Enter Project Data</h2>
                    <PortfolioForm addSection={this.addSection} />
                </React.Fragment>
            </PortfolioContext.Provider>
        )
    }
}

export default SubmitProject;

And also update your Portfolio component to use the PortfolioContext component to get the shared state: 并更新您的Portfolio组件以使用PortfolioContext组件来获取共享状态:

// Portfolio.jsx
import React from 'react';
import PortfolioContext from './PortfolioContext';

class Portfolio extends React.Component {
    //CAN I GET STATE FROM SubmitProject.js FILE IN HERE?
    render() {
        return(
            { /* Use the PortfolioContext.Consumer to access sections state */}
            <PortfolioContext.Consumer>
            {
                sections => (
                    <React.Fragment>
                        <h1>Portfolio Page</h1>
                        <h2>List of projects</h2>        
                        { /* here is the shared state - access and render section data as needed. This is just a demonstration to show how the data can be rendered in some way */ }
                        { Object.values(sections || {}).map(section => (<p>JSON.stringify(section)</p>) )}
                    </React.Fragment>
                )
            }
             </PortfolioContext.Consumer>
        )
    }
}

export default Portfolio;

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我将如何重组我的React App,以便可以将状态传递给另一条路线上的组件 - How would I restructure my React App, so that I can pass state down to a component on a different route 如何从 React 中的不同组件获取 state - How to get a state from a different component in React 在连接到不同状态部分的不同路由上重用react / redux组件 - Reusing react/redux component on different routes connected to different part of state 如何从不同的组件更改反应组件的 state? - How do you change state of a react component from a different component? 在react-redux应用程序中导航到其他路由时删除redux状态? - Delete redux state on navigating to a different route in react-redux application? State 不在不同的组件中更新 - State not updating in different component 如何在 React JS 中制作相同的 URL 方案但不同的路线和组件 - How to make same URL scheme but different route and component in React JS 只有一条子路线显示在反应中? 显示不同路线的组件而不是它自己的 - only one child route displaying in react? displays component for a different route instead of its own 从不同的组件设置状态 - setting state from a different component 如何根据redux状态使用相同的反应路由器路由绑定不同的反应组件? - How to Bind different react components with the same react-router route depending on redux state?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM