0

新从角度做出反应接收错误:

The above error occurred in the <div> component: in div
Consider adding an error boundary to your tree to customize error handling behavior.

我不太明白为什么 div 以及错误在说什么?我正在尝试单击一行并将值从行传递给父级。在我的顶级父组件中,我有一个函数可以设置所选行的值,在子组件中,所选行传递给道具。

家长:

class Parent extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      activeItem: []
    }

    this.setActiveItem = this.setActiveItem.bind(this)
  }

  setActiveItem = userSelect => {
    this.setState({ activeItem: userSelect })
  }

render(){
     <Child activeItem={this.setActiveItem}/>
}

在我的孩子中,我使用 ag-grid using onRowClicked. 错误被抛出this.props.setActiveItem(event.data)

class Child extends React.Component {
    constructor(props) {
        super(props)
     }
    onRowClicked = event => {
        //eslint-disable-next-line no-console
        console.log('tester', event.data) //okay, shows data
        this.props.setActiveItem(event.data) //not okay, throws error
      }

    grid = () => {
        return (
          <AgGridReact
            columnDefs={this.state.columnDefs}
            rowData={this.state.data}
            onRowClicked={this.onRowClicked}
          />
        )
      }
    render() {
        if (this.state.data.length > 0) {
          return <div className="ag-mod">{this.grid()}</div>
        }
        return <br />
      }
}
    //also here's the prop for child
    Child.propTypes = {
      setActiveItem: PropTypes.func
    }
4

1 回答 1

0

您正在将 setActiveItem 从父级传递给子级作为 activeItem。

<Child activeItem={this.setActiveItem}/>

所以在孩子中,用你在传递它时给出的名字来称呼它。

onRowClicked = event => {
    //eslint-disable-next-line no-console
    console.log('tester', event.data) //okay, shows data
    this.props.activeItem(event.data) //not okay, throws error
  }

此外,请考虑将您的组件包装在错误边界中,就像提到的错误一样。它有助于。你可以在这里阅读

于 2018-06-27T19:37:59.363 回答