【问题标题】:React Native Redux - Passing variable into dispatchReact Native Redux - 将变量传递给调度
【发布时间】:2018-09-12 15:18:16
【问题描述】:

给定一个 App.js 文件,其中包含这些用于 redux 的代码 sn-ps:

const initialState = {
    selection: ''
}

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'selection1':
            return { selection: 'selection1' }
        case 'selection2':
            return { selection: 'selection2' }
    }
    return state
}

const store = createStore(reducer)

还有一个带有选择器和 redux 调度的 Redux.js 子组件:

<Picker onValueChange={(itemValue) => this.props.changeSelection(itemValue)}>
    <Picker.Item label="Option1" value="selection1">
    <Picker.Item label="Option2" value="selection2">
</Picker>


function mapDispatchToProps(dispatch) {
    return {
        changeSelection: () => dispatch({ type: itemValue })
    }
}

我似乎无法弄清楚如何将选择器切换到的 itemValue 传递到调度中,然后更新 App.js 减速器中的状态。将 itemValue 传入 this.props.changeSelection() 然后将其设置为调度程序中的类型是否正确?

【问题讨论】:

    标签: javascript reactjs react-native redux react-redux


    【解决方案1】:

    你需要改变这一行

    changeSelection: () => dispatch({ type: itemValue })
    

    这条线

    changeSelection: (itemValue) => dispatch({ type: itemValue })
    

    changeSelection 应该有一个参数,即itemValue

    顺便说一句,我认为itemValue不应该设置在动作type中,它实际上与动作payload更相关,你可以发送这样的动作

    { type: 'UPDATE_SELECTION', payload: itemValue }
    

    那么你的减速器会是这样的

    const reducer = (state = initialState, action) => {
      switch (action.type) {
        case 'UPDATE_SELECTION':
            return { ...state, selection: action.payload }
      }
      return state
    }
    

    【讨论】:

    • 啊,我明白了,那真是个愚蠢的错误。感谢您的帮助。
    猜你喜欢
    • 2023-03-13
    • 2019-02-18
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    相关资源
    最近更新 更多