javascript - 如何在 React Redux 中实现自包含组件?

标签 javascript reactjs components redux react-redux

我正在构建一个基于react redux的文件管理器webui(我的目的是通过这个项目掌握react和redux)

如您所知,文件管理器需要一个树浏览器。我想构建一个可以包含它自身并且每个都有自身状态的组件。如下所示:

TreeNode 也可以包含 TreeNode 的子节点。每个 TreeNode 都保持其状态 {path, children_nodes, right ... ..}children_nodes是从server获取的,path是parent传递的。这就是我的想象。 结构如下:

App:
TreeNode
--TreeNode
----TreeNode
----TreeNode
TreeNode
TreeNode
--TreeNode
TreeNode
--TreeNode
----TreeNode
----TreeNode

但是麻烦来了,因为 redux connect 存储到树根,根下的所有节点都接收相同的状态...

例如,我有一个OPEN_NODE 操作,它被设计为触发getFileList 函数,基于该节点的路径并设置该节点的state.opentrue。(注意:getFileList 函数 尚未实现,暂时提供假数据) 屏幕截图: enter image description here

单击每个元素,但状态相同

我的代码:

容器/App.js

import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Footer from '../components/Footer';
import TreeNode from '../containers/TreeNode';
import Home from '../containers/Home';
import * as NodeActions from '../actions/NodeActions'

export default class App extends Component {

  componentWillMount() {
    // this will update the nodes on state
    this.props.actions.getNodes();
  }

  render() {
    const { nodes } = this.props
    console.log(nodes)
    return (
      <div className="main-app-container">
        <Home />
        <div className="main-app-nav">Simple Redux Boilerplate</div>
        <div>
          {nodes.map(node =>
            <TreeNode key={node.name} info={node} actions={this.props.actions}/>
          )}
        </div>

        {/*<Footer />*/}
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    nodes: state.opener.nodes,
    open: state.opener.open
  };
}


function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(NodeActions, dispatch)
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

容器/TreeNode.js

import React, { Component, PropTypes } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import classNames from 'classnames/bind'
import * as NodeActions from '../actions/NodeActions'

export default class TreeNode extends Component {

  constructor(props, context) {
    super(props, context)
    this.props = {
      open: false,
      nodes: [],
      info:{}
    }
  }

  handleClick() {
    let {open} = this.props
    if (open) {
      this.props.actions.closeNode()
    } else {
      this.props.actions.openNode()
    }
  }

  render() {
    const { actions, nodes, info } = this.props
    return (
      <div className={classNames('tree-node', { 'open':this.props.open})} onClick={ () => {this.handleClick()} }>
        <a>{info.name}</a>
        {nodes &&
          <div>{nodes.map(node => <TreeNode info={node} />)}</div>
        }
        {!nodes &&
          <div>no children</div>
        }
      </div>
    );
  }
}

TreeNode.propTypes = {
  open:PropTypes.bool,
  info:PropTypes.object.isRequired,
  nodes:PropTypes.array,
  actions: PropTypes.object.isRequired
}

Action /NodeActions.js

import { OPEN_NODE, CLOSE_NODE, GET_NODES } from '../constants/NodeActionTypes';

export function openNode() {
  return {
    type: OPEN_NODE
  };
}

export function closeNode() {
  return {
    type: CLOSE_NODE
  };
}


export function getNodes() {
  return {
    type: GET_NODES
  };
}

reducers/TreeNodeReducer.js

import { OPEN_NODE, CLOSE_NODE, GET_NODES } from '../constants/NodeActionTypes';

const initialState = {
  open: false,
  nodes: [],
  info: {}
}

const testNodes = [
  {name:'t1',type:'t1'},
  {name:'t2',type:'t2'},
  {name:'t3',type:'t3'},
]


function getFileList() {
  return {
    nodes: testNodes
  }
}


export default function opener(state = initialState, action) {
  switch (action.type) {
  case OPEN_NODE:
    var {nodes} = getFileList()
    return {
      ...state,
      open:true,
      nodes:nodes
    };
  case CLOSE_NODE:
    return {
      ...state,
      open:false
    };
  case GET_NODES:
    var {nodes} = getFileList()
    return {
      ...state,
      nodes:nodes
    };
  default:
    return state;
  }
}

完整代码见我的github https://github.com/eromoe/simple-redux-boilerplate

我没有看到涵盖此类组件的示例,谷歌搜索结果也没有任何帮助。 有什么办法可以克服这个问题吗?

更新: 我看到这个 How to manage state in a tree component in reactjs

但解决方案是将整棵树传递给状态,不能在文件管理器中使用。

最佳答案

我正在使用 React 和 Redux 实现类似 Github 的应用。

目前,我只列出存储库并显示其文件以及浏览它们。

我不知道这是好的还是坏的做法,但这就是我实现 Tree 组件的方式。

在每个树组件中,我都有一个指向自身的链接。我在路线上传递了一些数据,所以我能够在渲染它时获得下一棵树。

App

组件

class Tree extends Component {
  constructor(props) {
    super(props);

    this.renderList = this.renderList.bind(this);
  }

  componentWillMount() {
    this.props.getTree(this.props.params.sha);
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.params.sha !== this.props.params.sha) {
      this.props.getTree(nextProps.params.sha);
    }
  }

  renderList(file) {
    return (
      <tr key={ file.sha }>
        { file.type == 'tree'
       ? <td><Link to={`/repository/${this.props.params.repoName}/tree/${file.path}/${file.sha}`}>{ file.path }</Link></td>
       : <td><Link to={`/repository/${this.props.params.repoName}/blob/${file.sha}/${file.path}`}>{ file.path }</Link></td>}
      </tr>
    )
  }

  render() {
    const treeFile = this.props.tree;
    const fileName = this.props.params.path;

    return (
      <div className="row">
        <h3>{ fileName }</h3>
        <div className="col-md-12">
          <table className="table table-hover table-bordered">
            <tbody>
              { isEmpty(treeFile.tree) ? <tr>Loading</tr> : treeFile.tree.map(this.renderList) }
            </tbody>
          </table>
        </div>
      </div>
    )
  }
}
export default Tree;

Action

const setTree = (tree) => {
  return {
    type: actionTypes.GET_TREE,
    tree
  };
};

export const getTree = (sha) => {

  return (dispatch, getState) => {
    const { repository, profile } = getState();
    const repo = GitHubApi.getRepo(profile.login, repository.name);

    repo.getTree(sha, function(err, data) {
      dispatch(setTree(data));
    });
  }
}

reducer

const initialState = "";

export const tree = (state = initialState, action) => {
  switch (action.type) {
    case actionTypes.GET_TREE:
      return getTree(state, action);
  }
  return state;
}

const getTree = (state, action) => {
  const { tree } = action;
  return tree;
}

完整代码可以查看我在github上的仓库

https://github.com/glundgren93/Github-redux

关于javascript - 如何在 React Redux 中实现自包含组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37935756/

相关文章:

javascript - 子组件中的 onClick 操作发送了错误的元素

javascript - 输入类型= angularjs中的数字验证

javascript - 从本地托管网页的坐标获取元素详细信息

javascript - 如何在 React JS 应用程序中使用 webpack 在 img 标签中提供静态图像路径

html - 如何在 Angular 上明智地为组件 View 制作加载器

javascript - 无法读取未定义的属性 'Component' - React 组件插件的 webpack 构建

javascript - 动态命名的局部变量,用于加载模块

php - 在 PHP 中加载栏

javascript - 如何访问 next.js 应用程序中窗口对象上的 google api 脚本?

reactjs - 将参数传递给当前导入的类