U
U
usica2020-06-16 11:20:30
React
usica, 2020-06-16 11:20:30

Accessing state in a multi-page application?

The application has 2 components, one displays a variable, the other changes its value:

class Header extends React.Component {
  constructor() {super();}
    render() {return <div>{this.props.name}</div>}
}
class Catalog extends React.Component {
  constructor() {super();}
    render() {return <div onClick={this.props.changeName} >click</div>}
}
class App extends Component {
  constructor() {
        super();
        this.state = {
        	name:'test',
        }
        this.changeName = this.changeName.bind(this);
    }
    changeName(){
    this.state.name = 'new name';
        this.setState({name: this.state.name});
  }
  render() {
    return <div>
      <Header name={this.state.name} />
            <Catalog name={this.state.name} changeName={this.changeName} />
    </div>
  }
}


The Catalog component needs to be displayed only on one page, I do this https://webformyself.com/odnostranichnye-prilozhen...
render App now looks like this:
return (
            <div>
                <Header name={this.state.name} />
                <Menu />
                <Content />
            </div>
        );


content:
const Content = () => {
  return (
    <Switch>
      <Route exact path="/" component={pageIndex} />
      <Route path="/cart" component={pageCart} />
    </Switch>
  )
}

How to make a call on the page
<Catalog name={this.state.name} changeName={this.changeName} />
?

I ask at least to hint where to dig.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Egor Zhivagin, 2020-06-16
@Krasnodar_etc

If it needs to be displayed on the main page, add a call to pageIndex from your Content
If on the /cart page, then to pageCart from there
Or did I misunderstand the question?

R
Robur, 2020-06-16
@Robur

pass this.state.name to Content as a property, and in it already pass to catalog from props.

U
usica, 2020-06-16
@usica

Thanks for answers.
I'll post the solution in case it helps someone:

app:
<Content name={this.state.name} changeName={this.changeName} /> //здесь как обычно

content:
const Content = (parameters) => {
  return (
    <Switch>
      <Route exact path="/" component={() => (
            <PageIndex  parameters={parameters}/> )}/>//вот как передавать инфу
      
      <Route path="/cart" component={() => (
            <PageCart  parameters={parameters}/> )}/>
    </Switch>
  )
}

PageIndex:
const PageIndex = (parameters) => {
  let p = parameters.parameters;
  console.log(p.name);//данные переданы
}

Something like this.
It is not clear why parameters.parameters appeared at the end, but this is already easier to figure out.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question