使用 React 和一个

Webpage using React and one <div> id

本文关键字:一个 React 使用      更新时间:2023-09-26
id 的网页。

我仍在学习 React,发现它比我预期的要难一些,我也仍在学习 Web 开发。

如果我们的应用程序中只有一个视图,并且我们只有一个div,如下所示:

<body>
<div id="react-app"></div>
</body>

这是否意味着我们所有的 React 组件都将被追溯到一个 React 父组件?

这是否意味着当我们渲染页面时,我们只在顶级父组件上调用 render((,然后 React 将负责其余的工作?如果我们在等待数据,我们如何异步渲染子元素?

这是否意味着我们所有的 React 组件都将被追溯到一个 React 父组件?

是的。你的 React 应用程序将是一个具有单个顶级父节点的树。当该父节点被渲染时,React 将递归调用render,用于您在其父节点的render调用中声明的任何子组件。

如果我们在等待数据,我们如何异步渲染子元素?

React 的整个思想是声明你的 UI 在任何情况下的样子,例如初始状态、等待数据状态、数据返回状态和数据错误状态。

请考虑以下示例:

class App extends Component {
  constructor() {
    super()
    // set initial state
    this.state = { images: [], error: null }
    getDataFromServer('url').then(
      // success callback
      data => this.setState({ images: data.images }),
      // error callback
      data => this.setState({ error: data.error })
    )
  render() {
    return (
      <div>
        { // only render ImageGallery component if async call returns with data
          this.state.images.length > 0 && 
          <ImageGallery images={ this.state.images } />
        }
        { this.state.images.length === 0 &&
          <div>Loading / No images returned.</div>
        }
        { this.state.error &&
          <ErrorPopup error={ this.state.error } />
        }
      </div>
    )
  }
}

子组件依赖于父组件的状态,<App /> ,它以多种方式获取其状态,包括构造函数中的 ajax 调用(或componentWillMount, componentDidMount等(