什麼是React-redux、爲何使用React-redux、怎麼使用React-redux

一、什麼是React-reduxjavascript

React-redux是用於鏈接React和Redux的java

二、爲何使用React-reduxreact

使用React-redux能夠使redux部分代碼更簡潔更明瞭,好比組建中須要使用到的數據都在mapStateToProps方法中,組建中須要修改store的操做都在mapDispatchToProps中。redux

三、如何使用React-reduxdom

下面是一個簡單的例子ide

//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);
相關文章
相關標籤/搜索