给定一个带有以下代码片段的App.js文件以用于redux:

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 reducer中的状态。将itemValue传递到this.props.changeSelection()中,然后将其设置为调度程序中的类型是否正确?

最佳答案

您需要更改此行

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
}

09-25 17:13