【问题标题】:react+redux how can son component get props?react+redux 子组件如何获取props?
【发布时间】:2016-10-17 06:29:52
【问题描述】:

这是我的代码:
操作:
const increaseAction = { type: 'increase' }
reducer:

  // Reducer
  function counter(state = { count: 0 }, action) {
    const count = state.count
    switch (action.type) {
    ┊ case 'increase':
    ┊ ┊ return { count: count + 1 }
    ┊ default:
    ┊ ┊ return state
    }
  }

这是我的商店:
const store = createStore(counter)
和其他人:

  // Map Redux state to component props
  function mapStateToProps(state) {
    console.log(33333);
    return {
    ┊ value: state.count
    }
  }

  // Map Redux actions to component props
  function mapDispatchToProps(dispatch) {
    return {
    ┊ onIncreaseClick: () => {
    ┊ ┊ console.log(22222222222);
    ┊ ┊ dispatch(increaseAction)
    ┊ }
    }
  }

  // Connected Component
  const App = connect(
    mapStateToProps,
    mapDispatchToProps
  )(Main)


  ReactDOM.render(
    ┊ <Provider store={store}>
    ┊ ┊ <App />
    ┊ </Provider>,
    document.getElementById('content')
  );

**我的主要组件:**

>>class Main extends React.Component {
    constructor(props) {
    ┊ super(props);
    }
    render() {
      const {value, onIncreaseClick} = this.props;
    ┊ return (
    ┊ ┊ <div className={reactRootClass}>
    ┊ ┊ ┊ <div className='trade-left' onClick={onIncreaseClick}>
    ┊ ┊ ┊ </div>
    ┊ ┊ ┊ <div className='trade-right'>
    ┊ ┊ ┊ ┊ <Counter />
    ┊ ┊ ┊ </div>
    ┊ ┊ </div>
    ┊ )
    }
  }

这是我的问题:
现在,我可以拨打onIncreaseClick&lt;div className='trade-left' onClick={onIncreaseClick}&gt;

现在我想在我的&lt;Counter /&gt; 组件中调用onIncreaseClick,我怎样才能像在&lt;Main&gt; 组件中一样获得valueonIncreaseClickprops?
这是我的&lt;Counter&gt; 组件:

>>import React, { Component, PropTypes } from 'react'
  export default class Counter extends Component {
    render() {
    ┊ const { value, onIncreaseClick } = this.props
    ┊ return (
    ┊ ┊ <div>
    ┊ ┊ ┊ <span>{value}</span>
    ┊ ┊ ┊ <button onClick={onIncreaseClick}>Increase</button>
    ┊ ┊ </div>
    ┊ )
    }
  }

我只想在这打电话onIncreaseClick

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    您可以通过 MapStateToProps 方法将状态(给孩子)传递给孩子,类似地,您可以通过 mapDispatchToProps 函数将动作传递给孩子,如下所示:

    function mapDispatchToProps(dispatch) {
      const {updateData} = importedActions;
      return {
        actions: bindActionCreators({updateData}, dispatch),
      };
    }
    

    这是容器与层次结构中所有子组件通信的方式

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 2020-06-04
    • 1970-01-01
    • 2016-10-17
    • 2019-01-18
    • 2022-01-11
    • 2020-08-10
    相关资源
    最近更新 更多