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

栏目: 服务器 · 发布时间: 7年前

内容简介:注意:具体代码在参考;1. Button 的click事件中, 如果使用bind(this), 那么 bind(this, 33) 就可以把 33 作为参数传到这个方法中。

注意:具体代码在 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))
    }
  }
}

以上所述就是小编给大家介绍的《react - 20 redux 中传递parameter, click中传递参数》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

转型之战

转型之战

吴晓波 / 2015-7-1

互联网时代大潮席卷而来,互联网究竟是“魔法手杖”,还是“效率金箍棒”?传统企业如何正确借助和利用互联网思维帮助自身转变思维、完成企业转型升级?本书分两篇,上篇为传统行业互联网转型极具代表性和借鉴意义的案例,下篇精选吴晓波转型大课的独 家内容,梳理了吴晓波、刘伟、刘润、金霞、刘博、赵峰、张蕴蓝、张荣耀、李嘉聪、曾玉波等各行业10位导师关于互联网思维的精华理念和观点,其中囊括各传统行业互联网转型成功的......一起来看看 《转型之战》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

html转js在线工具
html转js在线工具

html转js在线工具