javascript - React Native Redux - 将变量传递到调度中

标签 javascript reactjs react-native redux react-redux

给定一个 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 }

那么你的 reducer 就会像这样

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

关于javascript - React Native Redux - 将变量传递到调度中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52298556/

相关文章:

javascript - 更新后的 Firebase-Functions 错误。我能做些什么?

javascript - 单击时更改输入占位符不透明度?

javascript - 在 React 渲染方法上解构 Prop 时的性能问题

Play 商店中 size = null 的 Android 应用

javascript - SafeAreaView 导致屏幕上出现奇怪的间隙

javascript - 如何在 javascript 中展平嵌套数组?

javascript - Canvas 图像遮蔽/重叠

testing - 使用 `import` 语句而不是 `require` 调用单个摩卡测试

reactjs - 如何在redux中过滤和排序相同的对象状态数组?

react-native - 尝试在 React Native 中使用文档选择器时无法读取未定义的属性(读取 'pick')