reactjs - 从 mongoDB 获取数据、setstate 并将 props 传递给子组件不起作用

标签 reactjs

下面是我的代码

class Root extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
    }
  }

  componentDidMount() {
    this.getDataFromDb();
  }

  getDataFromDb = () => {
    fetch('http://localhost:3001/getData')
      .then((data) => data.json())
      .then((res) => {
        if(res !== this.state.data) {        
          this.setState({ data: res}, () => console.log(this.state.data));
        }
      });
  };

  render() {
    return(
      <div>
        <IRPage data={this.state.data}></IRPage>
      </div>
    )
  }
}

class IRPage extends Component {

  print = () => {
    console.log(this.props.data);
  }

  render() {
    return (
      <div className="container m-5">
        <button onClick={this.print}></button>
      </div>
    )
  }
}

Root组件中getDatafromDB中setstate的回调函数工作成功, 但是当它传递给子组件 IRPage 并单击打印按钮时,结果是未定义的。 谢谢您的帮助

最佳答案

您的代码似乎按您的预期工作。

我尝试复制你写的内容并且它有效。结账这个jsfiddle

class Root extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
    }
  }

  componentDidMount() {
    this.getDataFromDb();
  }

  getDataFromDb = () => {
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then((data) => data.json())
      .then((res) => {
        if(res !== this.state.data) {        
          this.setState({ data: res}, () => console.log(this.state.data));
        }
      });
  };

  render() {
    return(
      <div>
        <IRPage data={this.state.data}></IRPage>
      </div>
    )
  }
}

// here I have added React to import Components from, because I don't know what import statement is
class IRPage extends React.Component {

  print = () => {
    console.log(this.props.data);
  }

  render() {
    return (
      <div className="container m-5">
        <button onClick={this.print}></button>
      </div>
    )
  }
}

ReactDOM.render(<Root />, document.querySelector("#app"))

关于reactjs - 从 mongoDB 获取数据、setstate 并将 props 传递给子组件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60246557/

相关文章:

ios - 为什么我不能在 iOS 上离开键盘以在 React Native App 中发送 Post?

javascript - 我们如何从 js Map 对象中删除特定对象?

reactjs - 未启用时,Android 的 React Native 运行速度非常慢 "Debug JS"

javascript - 如何在 TypeScript React 组件中返回字符串或 JSX 元素?

reactjs - Jest jest.mock函数具有不同的返回值

javascript - 使用 leaflet-geosearch 添加搜索栏

javascript - 多个状态在 React 中共享相同的 View 或组件

javascript - 在 componentDidMount 中 Promise 解析后响应 setState

javascript - 如何访问另一个文件中函数的状态

javascript - Sequelize,使用 React 删除多行