反应获取根组件的道具

时间:2019-03-22 09:28:52

标签: reactjs react-native react-redux

如何获取根组件的道具?

import React from 'react';
import { render } from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';

import cartReducer from './store/cartReducer'
import AddToCart from './cart/addToCart.jsx'

const store = createStore(cartReducer);


render(<Provider store={store}><AddToCart clicked={this.props.onIncrementCounter} />
       </Provider>, document.getElementById('addToCart'));  

有可能吗?因为出现错误:“无法读取未定义的属性'props'”。 我是React的新手。

这里是AddToCart组件

import React, { Component } from 'react';
import { connect } from 'react-redux';

class AddToCart extends Component {
    constructor(props) {
        super(props);
    }
}

const mapStateToProps = state => {
    return {
        items: state.cartItems,
        count: state.cartItemCount
    };
};

const mapDispatchToProps = dispatch => {
    return {
        onIncrementCounter: () => dispatch({ type: 'INCREMENT' })
    };
}

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

1 个答案:

答案 0 :(得分:2)

您收到此错误“无法读取未定义的属性'props'”,因为在代码的这一部分:<AddToCart clicked={this.props.onIncrementCounter} /> this引用了任何内容

您可以尝试这种方法:

import React from 'react';
import { render } from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';

import cartReducer from './store/cartReducer'
import AddToCart from './cart/addToCart.jsx'

const store = createStore(cartReducer);


render(<Provider store={store}><AddToCart/>
       </Provider>, document.getElementById('addToCart'));  

AddToCart.jsx

import React, { Component } from 'react';
import { connect } from 'react-redux';

class AddToCart extends Component {
    constructor(props) {
        super(props);
    }

    render() {
      return (
        <div onClick={this.props.onIncrementCounter}>
          Increment
        </div>
      )
    }
}

const mapStateToProps = state => {
    return {
        items: state.cartItems,
        count: state.cartItemCount
    };
};

const mapDispatchToProps = dispatch => {
    return {
        onIncrementCounter: () => dispatch({ type: 'INCREMENT' })
    };
}

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