Answer the question
In order to leave comments, you need to log in
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>
}
}
return (
<div>
<Header name={this.state.name} />
<Menu />
<Content />
</div>
);
const Content = () => {
return (
<Switch>
<Route exact path="/" component={pageIndex} />
<Route path="/cart" component={pageCart} />
</Switch>
)
}
<Catalog name={this.state.name} changeName={this.changeName} />
? Answer the question
In order to leave comments, you need to log in
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?
pass this.state.name to Content as a property, and in it already pass to catalog from props.
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);//данные переданы
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question