reactjs - 子组件列表未渲染

标签 reactjs

我尝试使用子组件渲染列表,但最终没有渲染任何内容。

PropertyBar 组件中的片段:

updateSelectedCell() {
    if (graph.selectedCell != null) {
      this.setState({
        selectedCell: graph.selectedCell,
        cellProperties: Array.from(graph.selectedCell.value.attributes)
      });
    }
  }

  renderPropertyList() {
    this.state.cellProperties.map(key => {
      <PropertyBarItem name={key.nodeName} value={key.nodeValue} />
    })
  }

  render() {
    if (this.state.selectedCell != null) {
      return (
        <div>
          <Button variant="contained" color="primary" fullWidth={true} onClick={() => this.updateSelectedCell()}> View properties </Button>
          <List>
            {this.renderPropertyList}
          </List>
        </div>
      )
    }
    return (
      <div>
        <Button variant="contained" color="primary" fullWidth={true} onClick={() => this.updateSelectedCell()}> View properties </Button>
        <List>
          <p>Click on a cell to view its properties.</p>
        </List>
      </div>
    )
  }

当用户单击按钮时,它会使用数组更新状态,然后使用数组内的键呈现 PropertyBarItem 列表。它最终不会显示任何内容,但不会崩溃。使用简单的 p 标签进行测试,它也不会渲染任何内容:

renderPropertyList() {
    this.state.cellProperties.map(key => {
      <p> {key} </p>
    })
  }

最佳答案

您没有调用renderPropertyList方法。添加 () 来调用它。

<div>
  <Button
    variant="contained"
    color="primary"
    fullWidth={true}
    onClick={() => this.updateSelectedCell()}
  >
    View properties
  </Button>
  <List>{this.renderPropertyList()}</List>
</div>

您还必须从 renderPropertyList 返回结果,并从给定 map 的函数返回 JSX。

renderPropertyList() {
  return this.state.cellProperties.map(key => {
    return <PropertyBarItem name={key.nodeName} value={key.nodeValue} />
  })
}

关于reactjs - 子组件列表未渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51830445/

相关文章:

javascript - React useCallback 钩子(Hook),未接收更新的依赖状态值

javascript - 将 useState setter 传递给 child 以更新 parent 状态是否正确?

javascript - 有没有办法使用 react 传单库使传单弹出响应?

javascript - 将react-select与formik一起使用时,无法读取未定义的属性 'type'

reactjs - 我想在react中使用withRouter从web服务获得响应后重定向到特定页面

reactjs - 如何使用 React Function Components 显示/隐藏微调器、 snackbar 或其他 transient 组件

javascript - "Unhandled Rejection (SyntaxError): Unexpected token h in JSON at position 0"与response.json()

reactjs - 在 react-admin 中创建自定义表单

javascript - 尝试让按钮在点击触发渲染后保持突出显示

wordpress - React/WordPress PWA 离线时不会响应 200