繁体   English   中英

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

[英]How to transfer data between pages in 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组件中显示所选项目

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

  • 要从父组件(在您的情况下为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中传递的回调,并将所需的数据作为该回调的参数传递(在您的示例中,可以选择此项)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM