react redux获得容器的属性

问题描述 投票:0回答:2

我在商店里有多个“部分”。每个部分都有一个object_id。

这是我的减速器部分:

export default function () {
  return [
    {
      object_id: 1,
      title: "section_1"
    },
    {
      object_id: 2,
      title: "section_2"
    },
    {
      object_id: 3,
      title: "section_3"
    }
  ]
}

我遍历商店部分并将它们添加到DOM中,但是当它们被添加时,自己的mapStateToPropsProps似乎是一个空对象。

import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';

class Section extends Component {

  render() {
    console.log(this.props.object_id);
  }

}

function mapStateToProps(state,ownProps) {
  return { 
    object_id: ownProps.object_id,
    sliders: state.sliders
  };
}

export default connect(mapStateToProps)(Section);

理想情况下,我希望能够遍历商店中的滑块,看看它们是否有一个与section_id相匹配的section_id,但是我已经陷入了第1步!

reactjs redux
2个回答
2
投票

在你的mapStateToProps选择器中,ownProps应该有object_id属性。假设state.sliders是一个数组,您可以使用.some检查数组中是否有匹配id的滑块。 .some如果找到则返回true,否则返回false。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

return {
  hasMatchingSlider: state.sliders.some(s => s.section_id === ownProps.object_id)
}

0
投票

所以看起来问题是 - 在添加部分的容器中,我还需要传递数据。所以:

  listSections(){
    return this.props.sections.map((section) => {
      return (
        <Section />
      );
    });
  }

变为:

  listSections(){
    return this.props.sections.map((section) => {
      return (
        <Section my_section_properties={section} />
      );
    });
  }

我现在可以访问我的section容器中的my_section_properties数据对象。

对于那些知道的人来说,这似乎是一种最佳实践方式吗?

© www.soinside.com 2019 - 2024. All rights reserved.