react - 20 redux 中传递parameter, click中传递参数

访问量: 38

注意:具体代码在  https://github.com/sg552/demo_redux_with_async_storage

参考;https://stackoverflow.com/questions/43017807/react-native-onpress-binding-with-an-argument

1. Button 的click事件中, 如果使用bind(this), 那么 bind(this, 33) 就可以把 33 作为参数传到这个方法中。

<Button
title={i18n.t('click_to_change_language', {locale: 'en'})}
onPress={this.changeLanguage.bind(this, 'en')}
>

2. redux中,如果要传递参数,该肿么办呢?

参考;https://stackoverflow.com/a/35769199/445908

2.1 action creator 中定义的方法要有参数,例如:

export const changeLanguage = (new_language) => {
  result= {
    type: CHANGE_LANGUAGE,
    new_language  // created a key named "new_language" with value such like 'en', 'zh'
  }
  return result
}

2.2 reducer 中要有处理的方法,见下面代码中的 action.new_language:

import { INCREASE_COUNT, CHANGE_LANGUAGE } from './types'

const initialState = {
  count: 0,
  language: 'en'
}

export const countReducer  = (state = initialState, action ) => {
  switch(action.type){
    case INCREASE_COUNT:
      console.info("== hi , before +1, count: " + state.count)
      return {
        count: state.count + 1
      }
    default:
      return state
  }
}

export const languageReducer = (state = initialState, action) => {
  switch(action.type){
    case CHANGE_LANGUAGE:
      return {
        language: action.new_language
      }
    default:
      return state
  }
}

2.3 视图中要传递参数,例如:

  changeLanguage(language){
    this.props.changeLanguage(language)
  }
//...
        <Button
          title={i18n.t('click_to_change_language', {locale: 'en'})}
          onPress={this.changeLanguage.bind(this, 'en')}
        >
        </Button>

2.4 最后,在mapDispatchToProps中,要修改:

const mapStateToProps = state => {
  return {
    count: state.countReducer.count,
    language: state.languageReducer.language
  }
}

const mapDispatchToProps = dispatch => {
  return {
    increaseCountByOne: () => {
      dispatch(increaseCount())
    },

    // 这里要把这个 new_language方法传递进来,上面的函数用来对比的
    changeLanguage: (new_language) => {
      dispatch(changeLanguage(new_language))
    }
  }
}

订阅/RSS Feed

Subscribe

分类/category