如何在Javascript地图中将道具传递给另一个组件?

时间:2016-08-10 21:44:05

标签: javascript reactjs redux

我有这段代码

import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import 'materialize-css/sass/materialize.scss';
import 'font-awesome/scss/font-awesome.scss';
import Storage from './Storage.js'
import {fetchStorage, loadAddStorageModal, selectStorage} from '../actions/StorageActions.js'


class SideNavContainer extends React.Component {
    componentWillMount() {        
        this.props.fetchStorage();
    }
    render() {
             console.log(this.props);
        return (
            <ul id="slide-out" className="side-nav fixed">      
                {
                    var hold = this.props;
                    this.props.storages.fetchedStorages.map(function (storage, i) {
                        return <Storage key={i} >{storage.name}</Storage>
                    })
                }
                <li>
                    <a className="waves-effect waves-light" onClick={() => this.props.loadAddStorageModal(true)}><i className="fa fa-plus" aria-hidden="true">Add</i></a>
                </li>
                <li className="hide-on-large-only"><a href="/Home/Index">Home</a></li>
                <li className="hide-on-large-only"><a href="/Account/SignOut">Signout</a></li>
            </ul>
        )
    }
}

function mapStateToProps(state) {
    return {
        storages: state.storages
    };
}

function matchDispatchToProps(dispatch){
    return bindActionCreators({fetchStorage: fetchStorage, loadAddStorageModal: loadAddStorageModal, selectStorage: selectStorage }, dispatch);
}


export default connect(mapStateToProps, matchDispatchToProps)(SideNavContainer);

我正在尝试将“this.props”传递到我的存储组件中。我试着做

 return <Storage {...this.props} key={i} >{storage.name}</Storage>

但我相信范围已经改变,因此不再适用。我试图把它放在一个名为“hold”的变量中,但这只会崩溃整个应用程序,因为它说“var”是一个意外的令牌。

1 个答案:

答案 0 :(得分:1)

使用fat arrow style function expression自动绑定this

this.props.storages.fetchedStorages.map((storage, i) => {
  return <Storage key={'storage-' + i} {...this.props}>{storage.name}</Storage>;
});