家长的状态未正确传递给孩子

时间:2018-12-02 16:08:54

标签: reactjs state lifecycle

我可以问一个非常简单的问题,为什么App状态不会传递给Child1的道具? 从以下代码中,Child1组件应在p标签中显示App的isLoggedIn,但不会显示它。您能为此提供一些建议吗?

App.js

import React, { Component } from "react";
import "./App.css";
import Child1 from "./Child1";

class App extends Component {
  constructor() {
    super();
    this.state = {
      isLoggedIn: false
    };
  }

  componentDidMount() {
    this.loginId = setInterval(() => {
      var loggedIn = Math.random() >= 0.5 ? true : false;
      this.setState({ isLoggedIn: loggedIn });
      console.log(this.state.isLoggedIn, "isLoggedIn");
    }, 3000);
  }

  render() {
    return (
      <div className="App">
        <Child1 isLoggedIn={this.state.isLoggedIn} />
      </div>
    );
  }
}

export default App;

Child1.js

import React, { Component } from "react";

class Child1 extends Component {
  render() {
    return (
      <div>
        <h1> Child 1 </h1>
        <p>Currently LoggedIn is {this.props.isLoggedIn}</p>
      </div>
    );
  }
}

export default Child1;

以下是我的反应版本信息。

"react": "^16.6.3",
"react-dom": "^16.6.3",
"react-scripts": "2.1.1"

enter image description here

1 个答案:

答案 0 :(得分:1)

无法显示布尔。 您可以这样做:

    <p>Currently LoggedIn is {this.props.isLoggedIn.toString()}</p>