首页 > 解决方案 > cellRendererParams 组件在第二个组件挂载后未收到道具

问题描述

我有一个基本网格,可以在其中一个单元格中呈现自定义组件,并且我还将一些道具传递给渲染器单元格内的该组件。这一切都适用于初始页面加载,但如果我转到另一条路线并返回具有 ag-grid 的旧路线,应用程序将崩溃,因为我的单元格渲染器组件不再接收道具。是什么导致了这种奇怪的行为?为什么它在初始页面加载时有效,但在其他组件生命周期中无效?

class UsersRoles extends Component {
  constructor(props) {
    super(props)
    this.state = {
      columnDefs: [
        {
          headerName: 'Phone',
          field: 'phone'
        },
        {
          headerName: 'Role',
          field: 'role'
        },
        {
          headerName: 'Edit',
          field: 'id',
          checkboxSelection: false,
          cellRenderer: 'EditIcon',
          cellRendererParams: (params) => {
            return {
              users: params.colDef.cellRendererParams.users,
              currentLoggedInUser: params.colDef.cellRendererParams.currentLoggedInUser,
              clickHandler: this.handleEditClick.bind(this)
            }
          },
        }
      ],
      frameworkComponents: {
        EditIcon
      }
    }

    this.handleEditClick = this.handleEditClick.bind(this)
  }

  componentDidMount() {
    this.props.fetchAllUsers()
  }

  handleEditClick(clickedUserId) {
    this.props.currentlyEditingUser(clickedUserId)
    this.props.openEditUserDetailsModal()
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevProps !== this.props) {
      const array = this.state.columnDefs
      array[4].cellRendererParams.currentLoggedInUser = this.props.currentLoggedInUser // update with loops instead of hardcode index selection
      array[4].cellRendererParams.users = this.props.users
      this.setState({ columnDefs: array })
    }
  }

  render() {
    return (
      <div style={styles.container}>
        <main style={styles.mainSection}>
          <CardSettings headline="Team members" size={{ flex: 3 }}>
            <div
              style={[styles.gridContainer, { width: '100%', height: '100%' }]}
              className="ag-theme-material custom-ag-theme ag-theme-material"
            >
              <AgGridReact
                columnDefs={this.state.columnDefs}
                rowData={this.props.users}
                frameworkComponents={this.state.frameworkComponents}
                suppressCellSelection
              />
            </div>
        </main>
      </div>
    )
  }
}

在初始页面加载时params,内部cellRendererParams包含所有数据,users但一旦 ag 网格组件卸载并再次安装,params则为空。

      cellRendererParams: (params) => {
        return {
          users: params.colDef.cellRendererParams.users,
          currentLoggedInUser: params.colDef.cellRendererParams.currentLoggedInUser,
          clickHandler: this.handleEditClick.bind(this)
        }
      },

如何确保我的单元格渲染器组件EditIcon始终接收usersandcurrentLoggedInUser道具,而不仅仅是在初始页面加载时?

标签: reactjsag-gridag-grid-react

解决方案


推荐阅读