繁体   English   中英

ReactJS使用函数修改this.props数据并将其存储到类变量中(例如RoR setter)

[英]ReactJS Modifying this.props data with a function and storing it into a class variable (like RoR setter)

我的react组件中有一个集合哈希数组,以这种格式存储在this.props.collections内部:

[{id: 1, title: 'sunglasses', other_data: 'yougetthepoint'},{hash2}..etc}]

我想使用以下函数将此格式转换为单个哈希

{ 'sunglasses': 1, 'necklaces': 2, etc}. 

如何将其存储到我的react组件中,以便可以查找每个标题的ID? 我认为这将类似于红宝石在路轨上的二传手。

function CollectionHash(){
  var obj = this.props.collections.reduce(function ( total, current ) {
    total[ current.title ] = current.id;
    return total;
  }, {});
  return obj;
}

完整的React组件

class ProductIndexPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      term: '',
      collection_id: null,
      products: this.props.products,
    };
    this.handleTermChange = this.handleTermChange.bind(this);
    this.handleCollectionChange = this.handleCollectionChange.bind(this);
  }

  handleTermChange(event) {
    this.setState({term: event}, () => {
      this.searchProducts()
    });
  }
  handleCollectionChange(event) {
    console.log('Handle Collection')
    console.log(this.collection_hash)
    console.log(event)
    this.setState({collection_id: event}, () => {
      this.searchProducts()
    });
  }
  render() {
    function CreateItem(product) {
      return { 
        url: '/products/' + product.id, 
        attributeOne: product.title,
        attributeTwo: product.variants[0].variant_price,
        attributeThree: '5 prices from $8.99 to $13.99',
        media: <Thumbnail
                  source={product.main_image_src}
                  alt={product.title}
                  size="small"
                />
      }
    }
    function CollectionTitles(collection) {
      return collection.title
    }
    function CollectionHash(){
      var obj = this.props.collections.reduce(function ( total, current ) {
        total[ current.title ] = current.id;
        return total;
      }, {});
      return obj;
    }
    return (
      <Layout>
        <Layout.Section>
          <Card title="Online store dashboard" actions={[{content: 'Edit'}]} sectioned>
            <Card.Section>
              <Stack>
                <TextField 
                  value={this.state.term}
                  label="Keyword Search"
                  placeholder="Enter Term"
                  onChange={this.handleTermChange}
                />
                <Select
                  value= {this.state.collection_id}
                  label="Collection"
                  options={ this.props.collections.map(CollectionTitles) }
                  placeholder="Select"
                  onChange={this.handleCollectionChange}
                  //onChange={this.valueUpdater('collection')}
                  //onChange={this.searchProducts('collection')}
                />
              </Stack>
            </Card.Section>
            <Card.Section>
                <ResourceList
                  items={
                      this.state.products.map(CreateItem)
                  }
                  renderItem={(item, index) => {
                    return <ResourceList.Item key={index} {...item} className='Polaris-Card' />;
                  }}
                />
            </Card.Section>
          </Card>
        </Layout.Section>
      </Layout>
    ); 
  }
searchProducts() {
  console.log('/products/' + "?term=" + this.state.term + "&collection=" + this.state.collection_id)
  $.ajax( {
    url: '/products/' + "?term=" + this.state.term + "&collection=" + this.state.collection_id,
    dataType: 'json',
    success: function(data) {
    this.setState({ products: data });
    }.bind(this),
    error: function(data) {
    }.bind(this)
   });
}

您的意思是如何使用javascript拼合数据吗? 如果是这样,你可以简单地做到这一点

let flatten = {};
(product).forEach((x)=>{ 
   flatten[x.title] = x.id;
});

为了使它在整个组件中都可访问,可以将局部变量“拉平”暴露给this.state或类似的方法

最好的祝福,

约翰·杰里科

原来,我不得不将其作为this.variable_name而不是var名称存储在构造函数中,而且我不能只是将函数放在构造函数之外并调用它并将其存储在var变量= CollectionHash()中。 请参阅下面的解决方案:

  class ProductIndexPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      term: '',
      collection_id: null,
      products: this.props.products,
    };
    this.handleTermChange = this.handleTermChange.bind(this);
    this.handleCollectionChange = this.handleCollectionChange.bind(this);
    this.col_hash = this.props.collections.reduce(function ( total, current ) {
        total[ current.title ] = current.id;
        return total;
      }, {});
  }

暂无
暂无

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

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