当先锋百科网

首页 1 2 3 4 5 6 7

Redux概述

在这里插入图片描述

Redux = Reducer + Flux

在这里插入图片描述

安装ant design

yarn add antd

Store的创建

src目录下, 创建store文件夹,创建文件index.js
index.js

import { createStore } from 'redux';
import reducer from './reducer';
const store = createStore(reducer);

export default store;

reducer.js

const defaultState = {
  inputValue: '123',
  list:[1,2]
}

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_todo_item') {
    const newState = JSON.parse(JSON.stringify(state));
    newState.list.push(newState.inputValue);
    newState.inputValue = '';
    return newState;
  }
  console.log(state, action);
  return state;
}

todoList.js

import store from './store';

class TodoList extends Component {
  constructor(props) {
    super(props);
    // 从store中取数据
    this.state = store.getState();
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleStoreChange = this.handleStoreChange.bind(this);
    this.handleBtnClick = this.handleBtnClick.bind(this);
    store.subscribe(this.handleStoreChange);
  }
}

安装redux 开发工具

  • 工具:redux devtools
  • 监听Input变化

TodoList.js

  <Input
    value = {this.state.inputValue}
    placeholder = "todo info"
    style = {{width: '300px', marginRight: '10px'}}
    onChange={this.handleInputChange}
  />
  <Button type="primary" onClick={this.handleBtnClick}>提交</Button>
handleInputChange(e) {
  const action = {
	type: 'change_input_value',
	value: e.target.value
  }
  store.dispatch(action);
}

handleStoreChange() {
  // console.log('store changed');
  this.setState(store.getState());
}

handleBtnClick() {
  const action = {
    type: 'add_todo_item'
  };
  store.dispatch(action);
}

Redux注意点

  • store是唯一的
  • 只有store能改变自己的内容
  • Reducer必须是纯函数

Redux API

  • createStore
  • store.dispatch
  • store.getState
  • store.subscribe