【问题标题】:Render state in another component in reactjs在 reactjs 的另一个组件中渲染状态
【发布时间】:2019-10-14 22:53:45
【问题描述】:

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

这里是我初始化用户名(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}

【问题讨论】:

    标签: reactjs state


    【解决方案1】:

    这里有一个关于How to pass component via react router的很好的讨论。

    在讨论之后,您的代码将如下所示:

    <div className="App">
          <Router history={history}>
            <Switch>
              <!-- Pass username as props here -->
              <Route path="/your-route" render={()=><Projects username={this.state.username}/>} />
            </Switch>
          </Router>
    </div>
    

    在您的 Projects 组件中,您可以使用 this.props.username 检索它。

    【讨论】:

      【解决方案2】:

      您的项目组件无权访问App 中的状态。

      您应该使用像 React ContextRedux 这样的状态管理器来执行此操作

      【讨论】:

        【解决方案3】:

        这是行不通的,你不能直接在所有子组件中访问父组件的状态, 您必须将父状态作为道具发送给子组件才能访问它们。

        在这种情况下,您希望在所有子组件中使用一种状态,使用 Redux 是一件好事,它将为您提供一个全局状态,您的所有组件都可以访问该状态。 你也可以通过 React 的Context API 解决这个问题。

        【讨论】:

          【解决方案4】:

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-09-04
            • 2018-08-01
            • 2020-10-21
            • 2019-08-08
            • 2021-02-16
            • 1970-01-01
            • 2017-10-20
            • 1970-01-01
            相关资源
            最近更新 更多