Set default props for a react Component

2019-02-18 19:49发布

问题:

I want my app component has a default props , and use that props in mapStateToProps.

containers/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 {

  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);

reducers/TreeNodeReducer.js

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;
  }
}

I have tried :

1: constructor

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

2: defaultProps:

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

but none of them work... log always is:

state has the correct default value, but ownProps is empty...

PS:Project is here .

回答1:

1) two "export default"

you're doing two export default into App.js.

Try changing:

export default class App extends Component

to

const App = class App extends Component.

And then:

...

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

2) "defaultProps" and "ownProps":

As mapStateToProps is being called before the component construction (when defaultProps are defined), the ownProps is empty. You can try two options:

1) this workaround:

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) apparently, ownProps first call is feeded with the inline defined props. So, you can call <App /> this way in the index.js:

<App info={{ path:'/' }} />

Anyway, after solving this, another error is thrown (Cannot read property '/' of undefined) when trying to read tree from the reducer (doesn't exist there).



回答2:

I found a better way to set defaultProps,

Because connect() returns a new component. If you'd like defaultProps to be present on it, you need to put defaultProps on it:

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

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

export default App

This would work!