首页 > 解决方案 > 在 reactjs 的另一个组件中渲染状态

问题描述

我正在尝试在不同的组件中显示当前用户名,但它不起作用,我做错了什么?

这是我初始化用户名(App.js)的地方

class App extends Component{
  constructor(props) {
    super(props);
    this.state = {
      logged_in: localStorage.getItem('token') ? true : false,
      username: ''
    };
  }
  componentDidMount() {
    if (this.state.logged_in) {
      fetch('http://localhost:8000/user/current_user/', {
        headers: {
          Authorization: `JWT ${localStorage.getItem('token')}`
        }
      })
        .then(res => res.json())
        .then(json => {
          this.setState({ username: json.username });
          console.log(json.username);
        });

    }
  }
  render() {
  return (
    <div className="App">
      <Router history={history}>
        <Switch>
          <Route exact path="/" component={First} />
          <Route path="/home" component={Projects} />
          <Route path="/menu" component={MenuH} />
          <Route path ="/createProject" component={CreateP} />
          <Route path ="/connect" component={Newacount} />
          <Route component={Notfound} />
        </Switch>
      </Router>
    </div>
  );
  }
}
...

这就是我在不同的组件(项目)中调用它的方式

{this.state.username}

标签: reactjsstate

解决方案


尝试将状态作为孩子的道具发送并从孩子那里访问!或者直接访问状态,你可以使用 redux store 或 react 的 context api!

<Route path="/home" render={()=><Home username={this.state.username} />} />

推荐阅读