将状态传递给 React/Redux 中的递归嵌套组件

IT技术 reactjs redux material-ui react-redux
2021-05-02 03:55:40

我有一个组件,它的子组件与组件本身的类型相同。我也可以渲染孩子,但孩子们似乎无法访问他们的状态。我在 Redux 中使用 React

export class Material extends React.Component {

  constructor(props) {
    super(props)
    this.renderChild = this.renderChild.bind(this)
    this.getNestedItems = this.getNestedItems.bind(this)
  }

  static propTypes = {
    parentId: PropTypes.number,
    id: PropTypes.number.isRequired,
    name: PropTypes.string.isRequired,
    subtext: PropTypes.string.isRequired,
    childIds: PropTypes.arrayOf(PropTypes.number.isRequired),
    fileType: PropTypes.string.isRequired
  }

  // This is where I am having trouble.
  // Shouldn't the props be accessible from state itself?

  renderChild = (id, childId) => (
      <Material key={childId}
        id={childId}
        parentId={id}
        name={name}
        subtext={subtext}
        fileType={fileType}
        />
    )

  getNestedItems = (id, childIds) => {
    console.log("id: " + id)
    console.log("childIds: " + childIds)
    var childItems = []
    for(var i=0; i < childIds.length; i++){
        var child = this.renderChild(id, childIds[i])
        childItems.push(child)
    }
    return childItems
  }

  render(){

    let childItems = []
    if(this.props.childIds){
      childItems = this.getNestedItems(this.props.id, this.props.childIds)
    }

    return(
      <ListItem
        leftAvatar={<Avatar icon={fileType.length === 0 ? <FileFolder /> : <ActionAssignment />} />}
        rightIcon={fileType.length === 0 ? <AddCircle /> : <ActionInfo />}
        primaryText={name}
        secondaryText={subtext}
        initiallyOpen={fileType.length === 0} // fileType is empty if it is a folder
        primaryTogglesNestedList={fileType.length === 0}
        nestedItems={childItems} // one has to pass an array of elements
      />
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    id: ownProps.id,
    name: state.Material[ownProps.id].name,
    subtext: state.Material[ownProps.id].subtext,
    childIds: state.Material[ownProps.id].childIds,
    fileType: state.Material[ownProps.id].fileType,
  }
}

export default connect(
  mapStateToProps
)(Material)

此外,我正在使用Material-ui 中ListItem(这些最终呈现在 List 组件中)并且我的代码受到官方 redux 存储库中树视图示例的严重影响我的状态是这样的:

const initialState = {
  0: {
      id: 0,
      name: 'Root',
      subtext: 'Some subtext',
      fileType: '',
      childIds: [1]
    },
  1: {
      id: 1,
      name: 'Child',
      subtext: 'Child subtext',
      fileType: 'png',
      childIds: []
    }

}

显示的状态与树视图示例具有相同的结构

1个回答

好吧,如果我理解正确的话,您希望这些Material组件从 redux 存储中获取它的数据。
如果这是您想要实现的目标,则需要为每个Material. 基本上你需要用connectHOC包装所有这些
例子:

const MaterialContainer = connect(mapStateToProps)(Material);

renderChild函数内部,您将使用 this MaterialContainer

renderChild = (id) => (
  <MaterialContainer key={childId} id={childId} />
)

你可以看到它在这里工作 https://jsbin.com/taquke/edit?js,output