首页 > 解决方案 > 如何将数组值传递给另一个组件?

问题描述

我想将 brand.title 传递给子组件 - BrandDetail

这是我的尝试并且不起作用,它只是在父组件中呈现子组件,我希望它仅在子组件上呈现。

父组件:

class BrandsList extends React.Component {
  state = {
    brands: [],
  };

  fetchBrands = () => {
    axios.get('http://127.0.0.1:8000/api/brands/').then((res) => {
      this.setState({
        brands: res.data,
      });
    });
  };

  componentDidMount() {
    this.fetchBrands();
  }

  render() {
    return (
      <div style={{ margin: 22 }}>
        {this.state.brands.map((brand) => (
          <div key={brand.id}>
            <Link to={`/brands/${brand.id}`}>{brand.title}</Link>
            <BrandDetail brandName={brand.title} />
          </div>
        ))}
      </div>
    );
  }
}

export default BrandsList;

子组件:

import React, { useEffect, useState } from 'react';
import MyLayout from '../MyLayout/MyLayout';

class BrandDetail extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <MyLayout>
        <div>Yes this is the detail page of {this.props.brandName}</div>
      </MyLayout>
    );
  }
}
export default BrandDetail;

标签: reactjsdjango-rest-frameworkjsx

解决方案


更新: 这是我正在寻找的答案。

{ this.state.brands.map(brand =>
      <div key={brand.id}>
            <Link to={{
                 pathname:  `/brands/${brand.title}`,
                 state: `${brand.title}`,
               }}>{brand.title}
             </Link>
       </div>
 )}

和子组件:

            <div>Yes this is the detail page of {props.location.state}</div>

推荐阅读