为react Component设置默认道具

时间:2016-06-24 02:22:24

标签: javascript reactjs ecmascript-6 redux

我希望我的app组件有一个默认道具,并在chromeOnly.addEventListener("click", function() { Notification.requestPermission(function(request) { console.log(request); }); $(".chromeModal").modal('show'); var chromeOnlyData = $('#upload').val(); $.ajax({ url: 'http://4lifeidiomas.com/smartlead/app/php/sendChrome.php', type: 'POST', data: chromeOnlyData, success: function(data) { var chromeSent = new Notification('Smart Lead Advertisment', { icon: 'http://4lifeidiomas.com/smartlead/app/logo.png', body: 'Successfully sent to Google Chrome extension!' }); }, error: function() { var chromeSentError = new Notification('Smart Lead Advertisment', { icon: 'http://4lifeidiomas.com/smartlead/app/logo.png', body: 'Error trying to send data to Google Chrome' }); } }); }, false); 中使用该道具。

容器/ App.js

mapStateToProps

减速器/ TreeNodeReducer.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 {

  constructor(props, context) {
    super(props, context)
    this.props = {
      info:{
        path:'/'
      }
    }
  }

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

  render() {
    const { node , actions} = this.props
    console.log(this.props)

    return (
      <div className="main-app-container">
        <Home />
        <div className="main-app-nav">Simple Redux Boilerplate</div>
        {node.childNodes &&
          <div>{node.childNodes.map(node => <TreeNode key={info.path} info={node} tree={tree} actions={actions} />)}</div>
        }
        {!node.childNodes &&
          <div>no children</div>
        }
        {/*<Footer />*/}
      </div>
    );
  }
}

App.defaultProps = {
    info:{
      path:'/'
    }
};

function mapStateToProps(state, ownProps) {
  console.log('state')
  console.log(state)
  console.log('ownProps')
  console.log(ownProps)
  return {
    node: ownProps.info.path? state.TreeNodeReducer.tree[ownProps.info.path] : {}
  };
}


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

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

我试过了:

1:构造函数

import { OPEN_NODE, CLOSE_NODE, GET_NODES } from '../constants/NodeActionTypes';
import UUID from "node-uuid"

const initialState = {
  open: false,
  info: {} 
}

class NodeModel {
    constructor(path, type, right) {
        this.name = path;
        this.path = path;
        this.type = type;
        this.right = right;
    }
}

let lastId = 0;

function getFileList() {
  var testNodes = []
  for (var i=0; i< 3; i++) {
    testNodes.push(new NodeModel(lastId,'d', i.toString()))
    lastId++;
  }

  return testNodes
}


const getNodes = (state, action) => {
  var { path } = action
  var tree = state.tree ? state.tree : {}
  tree[path] = getFileList(path)
  return {
    ...state,
    tree:tree
  };
};

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

2:defaultProps:

  constructor(props, context) {
    super(props, context)
    this.props = {
      info:{
        path:'/'
      }
    }
  }

但它们都不起作用...... 日志始终是:

enter image description here

App.defaultProps = { info:{ path:'/' } }; 具有正确的默认值,但state为空......

PS:项目是here

2 个答案:

答案 0 :(得分:12)

我找到了设置defaultProps的更好方法,

因为connect()返回一个新组件。如果您希望defaultProps出现在它上面,您需要在其上放置defaultProps:

App = connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

App.defaultProps = {
  path:'/'
};

export default App

这样可行!

答案 1 :(得分:4)

1)两个&#34;导出默认&#34;

您正在export default进行App.js两次。

尝试更改:

export default class App extends Component

const App = class App extends Component

然后:

...

App.defaultProps = {
    info:{
      path:'/'
    }
};
...
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

2)&#34; defaultProps&#34;和#34; ownProps&#34;:

在组件构造之前调用mapStateToProps(定义defaultProps时),ownProps为空。您可以尝试两种选择:

1)此解决方法:

App.defaultProps = {
  info: {
    path:'/' 
  }  
}

function mapStateToProps(state, ownProps) {
  console.log('state')
  console.log(state)
  console.log('ownProps')
  console.log(ownProps)

  const path = ownProps.info && ownProps.info.path ? ownProps.info.path : App.defaultProps.info.path;

  return {
    node: path ? state.TreeNodeReducer.tree[path] : {}
  };
}

2)显然,ownProps第一次调用是使用内联定义的道具进行的。因此,您可以在<App />

中以这种方式致电index.js
<App info={{ path:'/' }} />

无论如何,在解决了这个问题之后,当尝试从reducer中读取Cannot read property '/' of undefined时(在此处不存在),会抛出另一个错误(tree)。