什么是React-redux、为什么使用React-redux、怎么使用React-redux

1、什么是React-redux

React-redux是用于连接React和Redux的

2、为什么使用React-redux

使用React-redux可以使redux部分代码更简洁更明了,比如组建中需要使用到的数据都在mapStateToProps方法中,组建中需要修改store的操作都在mapDispatchToProps中。

3、如何使用React-redux

下面是一个简单的例子

//store/index.js 
//store部分的代码和没有使用react-redux时相同
import { createStore } from 'redux'
import reducer from './reducer';
const store = createStore(reducer);

export default store;
//reducer.js
//reducer部分和未使用react-redux时相同
const defaultState = {
  inputValue: '',
  list: []
}
//reducer 可以接受state但是不能修改state,需要对state进行深拷贝
export default (state = defaultState, action) => {
  if (action.type === 'change_input_value') {
    const newState = JSON.parse(JSON.stringify(state));
    newState.inputValue = action.value;
    return newState
  }
  if (action.type === 'add_input_value') {
    const newState = JSON.parse(JSON.stringify(state));
    newState.list = [...state.list, state.inputValue]
    newState.inputValue = '';
    return newState;
  }
  return state;
}
//index.js
//入口需要稍微调整

import React from 'react';
import ReactDOM from 'react-dom';
import TodoList from './TodoList';
import { Provider } from 'react-redux';
import store from './store';

ReactDOM.render(
  <Provider store={store}>
    <TodoList />
  </Provider>, 
document.getElementById('root')
);
import React, { Component, Fragment } from 'react';
import { connect } from 'react-redux';

class TodoList extends Component {
  constructor(props){
    super(props)

    this.handleList = this.handleList.bind(this);
  }
  handleList(){
    return this.props.list.map((item) => {
      return <li>{item}</li>
    })
  }
  render() {
    return (
      <Fragment>
        <div>
          <input 
            value = {this.props.inputValue} 
            onChange = {this.props.handleInputChange}
          />
          <button onClick={this.props.btnClick}>提交</button>
        </div>
        <ul>
          {this.handleList()}
        </ul>
      </Fragment>
    );
  }
}
function mapStateToProps(state) {
  return {
    inputValue: state.inputValue,
    list: state.list
  }
}
function mapDispatchToProps(dispatch) {
  return {
    handleInputChange:function(e){
      const action = {
        type: 'change_input_value',
        value: e.target.value
      }
      dispatch(action);
    },
    btnClick:function(){
      const action = {
        type: 'add_input_value'
      }
      dispatch(action);
    }
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(TodoList);

 

转载于:https://my.oschina.net/kimyeongnam/blog/1860097

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值