0

给定一个 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 减速器中的状态。将 itemValue 传入 this.props.changeSelection() 然后将其设置为调度程序中的类型是否正确?

4

1 回答 1

3

您需要更改此行

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

通过这条线

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

changeSelection应该有一个参数,即itemValue

顺便说一句,我认为itemValue不应该设置在 actiontype中,它实际上与 action 更相关payload,你可以像这样 dispatch 一个 action

{ type: 'UPDATE_SELECTION', payload: itemValue }

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

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'UPDATE_SELECTION':
        return { ...state, selection: action.payload }
  }
  return state
}
于 2018-09-12T15:21:19.433 回答