简体   繁体   中英

Error passing state in REACT from App.js to Component.js via route

So I've been learning React for a while, but one of the key's in what I have yet succeeded is passing states.

What I'm trying to do is passing a state from my App.js to a component rendered via route. Unfortunately, in MyComponent.js, I get error message 'lang is undefined'.

Can someone guide me to a solution? This is what I have so far:

App.js

class App extends Component {

constructor (props) {
    super (props)
    this.state = {
        language: 'en'
    }
}   
render() {
    return (
        <BrowserRouter>
            <div className='App'>
                <Switch>
                    <Route 
                    exact path='/' render={(props) => <MyComponent lang={this.state.language} />}
                    />
                    <Route exact path='/privacy/policy' component={Policy} />
                    <Route path='*' component={NotFound} />
                </Switch>
            </div>
        </BrowserRouter>
    );
} } export default App;

MyComponent.js

export class MyComponent extends Component {

constructor(props) {
    super(props);
    this.state = {
        lang : {lang} 
    }
}
render () {
    return (
        <div className='searchBar'>
            <p>Current language is: {this.state.lang}</p>// HERE COMES THE STATE
        </div>
    );
}}

You are trying to pass props down to MyComponent component but you are trying to render it in SearchBar component. Rename SearchBar to MyComponent in the first route of your App.js .

Also, in MyComponent.js , remove the lang property from state and change:

<p>Current language is: {this.state.lang}</p>

to

<p>Current language is: {this.props.lang}</p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM