简体   繁体   English

如何将 object 传递给 react-redux

[英]How to I pass an object to react-redux

I'm a little confused on passing an object to the redux store.将 object 传递给 redux 商店时,我有点困惑。 I have successfully created the store and can add items from the initial state.我已经成功创建了商店,并且可以从最初的 state 添加项目。 The function also fires when called function 在调用时也会触发

Action:行动:

import { GET_ITEM } from './OrderTypes'

export const getItem = (payload) => {
    return {
        type: GET_ITEM,
        payload: { payload }
    }
}

Reducer:减速器:

import { GET_ITEM } from './OrderTypes'

const initialState = {
    orderList: [],   
}

const orderReducer = (state = initialState, action) => {
    switch (action.type) {
        case GET_ITEM: return {
            ...state,            
            orderList: [...state.orderList, action.payload]           
        }
        default: return state        
    }
}

export default orderReducer

Component:零件:

class TestComponentextends Component {

  pushItem = () => {
    this.props.getItem({
      payload: 'test object'
    })
  }

  render() {
    return (
      <input type='button' value='test btn' onClick={this.pushItem} />
    )
  }
}

const mapStateToProps = state => {
  return {
    orderList: state.orderList
  }
}

const mapDispatchToProps = dispatch => {
  return {
    getItem: () => dispatch(getItem())
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(TestComponent)

What happens: An empty object is added to the orderList array.会发生什么:将一个空的 object 添加到 orderList 数组中。

What I want to happen: Store the object in pushItem in the orderList array.我想要发生的事情:将 object 存储在pushItem数组中的 pushItem 中。

Your mapDispatchToProps doesn't pass the arguments to the action creator ( see mapDispatchToProps function arguments - 2nd example):您的mapDispatchToProps没有将 arguments 传递给动作创建者( 请参阅mapDispatchToProps function arguments - 第二个示例):

const mapDispatchToProps = dispatch => ({
  getItem: (...args) => dispatch(getItem(...args))
})

Even easier is to let react-redux handle the mapping by using mapDispatchToProps as an object :更简单的是让react-redux使用mapDispatchToProps作为 object来处理映射:

const mapDispatchToProps = {
  getItem
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM