如何在Reactjs中的页面之间传输数据

时间:2019-05-02 09:19:19

标签: javascript reactjs

我正在尝试将数据从DropDownItem组件传输回我的类组件,而我无法使用props来完成。 在此示例中,我想将props.product的点击项转移到我的应用程序组件中。 谁能告诉我最好的方法是什么? 预先感谢。

当我单击下拉选项时,我想将其显示为我的实例 主类组件。 我已经尝试为此目的创建一个特殊的组件,但这会使代码变得非常复杂。

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      products: []
    }
  }

  async fetchDevices() {

    const url = 'my url';
    const response = await fetch(url, { method: 'GET', headers: headers });
    const data = await response.json()
    this.setState({ products: data.value })
  }


  componentDidMount() {
    this.fetchDevices();
  }

  render() {
    const productItems = this.state.products.map((productValue, index) => {
      return (<DropDownItem key={index} product={productValue.name} />)
    })

    return (
      <div>

        {this.state.products[0] && Array.isArray(this.state.products) ?
          <div>
            <DropdownComponent
              isOpen={this.state.dropdownOpen}
              toggle={this.toggle}
              product={productItems}
            />
          </div> :
          <div>loading...</div>}
        <p></p>
      </div>

    )
  }
}

export default App

function DropDownItem(props) {
  return (
    <div>
      <DropdownItem onClick={() => console.log("selected product", props.product)}>
        {props.product}</DropdownItem>
      <DropdownItem divider />
    </div>
  )
}
export default DropDownItem

我想在我的App组件中显示所选项目

1 个答案:

答案 0 :(得分:0)

组件之间数据传输的一般规则是:

  • 要从父项(在您的情况下为App到子项(DropDownItem)转移,请使用props
  • 要从子级转移到父级(要执行的操作)-使用带有相关参数的回调

示例(未经测试,仅用于展示想法)

// App component
...
selectDropDownItem(item) {
    this.setState({selectedItem: item});
}

render () {
    return 
    // ...
    <DropdownComponent
      isOpen={this.state.dropdownOpen} 
      toggle={this.toggle}
      product={productItems}
      selectItemCallback={this.selectDropDownItem.bind(this)}/>
    //...

// DropDownItem component

function DropDownItem (props) {

 return (
<div>

// bind to props.product so when called props.product will be passed as argument
<DropdownItem onClick={props.selectItemCallback.bind (null, props.product)}>
{props.product}</DropdownItem>
<DropdownItem divider/>
</div>
)  
}

export default DropDownItem

一般的想法是您将回调从父级传递给子级。当孩子需要与父母沟通时,它只调用在props中传递的回调,并将所需数据作为该回调的参数传递(在您的示例中,可以选择此项)