美文网首页
2021-03-25 react redux thunk

2021-03-25 react redux thunk

作者: FConfidence | 来源:发表于2021-03-25 22:18 被阅读0次

父组件

import React, { Component } from 'react';
import Form from './Form';
import List from './List';
import { Provider } from 'react-redux';
import store from './store/index';

export default class TodoListPage extends Component {
  render(): React.ReactElement {
    return (
      <Provider store={store}>
        <List></List>
        <Form></Form>
      </Provider>
    );
  }
}

store 数据存储

import { createStore, applyMiddleware } from 'redux';
import reduxThunk from 'redux-thunk';

import reducer from './reducer';

const middleWare = applyMiddleware(reduxThunk);

export default createStore(reducer, middleWare);

reducer

export interface IcState {
  count: number;
  list: Array<any>;
}

export enum ACTION_TYPES {
  LOAD_DATA,
  PUT_DATA,
  DELETE_DATA,
}

const defaultState: IcState = {
  count: 0,
  list: ['Task 1', 'Task 2', 'Task 3'],
};

export default (state = defaultState, action: any) => {
  switch (action.type) {
    case ACTION_TYPES.LOAD_DATA: {
      return {
        ...state,
        list: action.data,
      };
    }
    case ACTION_TYPES.PUT_DATA: {
      return {
        ...state,
        list: [...state.list, action.task],
      };
    }
    case ACTION_TYPES.DELETE_DATA: {
      const list = state.list.filter((_: any, index: number) => {
        return index !== action.index;
      });
      return {
        ...state,
        list,
      };
    }
    default: {
      return state;
    }
  }
};

actionCreator

import { ACTION_TYPES } from './reducer';

export const removeAction = (index: number): any => {
  return {
    type: ACTION_TYPES.DELETE_DATA,
    index,
  };
};

export const putDataAction = (task: string): any => {
  return {
    type: ACTION_TYPES.PUT_DATA,
    task,
  };
};

export const setDataAction = (data: any): any => {
  return {
    type: ACTION_TYPES.LOAD_DATA,
    data,
  };
};

// 异步的action
export const loadDataAction = () => {
  return async (dispatch: any) => {
    fetch('/list_data.json')
      .then((resp: any) => resp.json())
      .then((resp: any) => {
        let { data } = resp;
        data = data
          .map((item: any) => item?.item_info?.article_info?.brief_content)
          .filter((item: any) => item)
          .slice(0, 5);
        dispatch(setDataAction(data));
      });
  };
};

List注入数据

import React, { Component } from 'react';

import { connect } from 'react-redux';
// import { ACTION_TYPES } from './store/reducer';
import { removeAction, loadDataAction } from './store/actionCreator';

// 映射state到当前组件的props上
const mapStateToProps = (state: any): any => {
  return {
    list: state.list,
  };
};

// 映射dispatch映射到props上
const mapDispatchToProps = (dispatch: any) => {
  return {
    remove(index: number): any {
      dispatch(removeAction(index));
      /*
      dispatch({
        type: ACTION_TYPES.DELETE_DATA,
        index,
      });
      */
    },
    loadData() {
      dispatch(loadDataAction());
    },
  };
};

class List extends Component {
  public async componentDidMount() {
    /*
    const resp: any = await fetch('/list_data.json');
    (this.props as any).loadData(resp.data);
    */
    (this.props as any).loadData();
  }

  private handleClick(index: number): any {
    return () => {
      (this.props as any).remove(index);
    };
  }
  render(): React.ReactElement {
    const { list } = this.props as any;
    return (
      <div>
        <ul>
          {list.map((item: any, index: number) => (
            <li key={item}>
              <span>{item}</span>
              <button className="btn" onClick={this.handleClick(index)}>
                remove
              </button>
            </li>
          ))}
        </ul>
      </div>
    );
  }
}

// 该方法的返回值是一个高阶组件(函数)
export default connect(mapStateToProps, mapDispatchToProps)(List);

Input注入数据

import React, { Component } from 'react';

import { connect } from 'react-redux';
import { putDataAction } from './store/actionCreator';
// import { ACTION_TYPES } from './store/reducer';

// 映射dispatch映射到props上
const mapDispatchToProps = (dispatch: any): any => {
  return {
    putData(task: any): any {
      dispatch(putDataAction(task));
      // dispatch({
      //   type: ACTION_TYPES.PUT_DATA,
      //   task,
      // });
    },
  };
};

interface IcState {
  task: string;
}

// interface IcProps {}

class Form extends Component<any, IcState> {
  state = {
    task: '',
  };

  public handleChange: React.ChangeEventHandler<HTMLInputElement> = (
    event: React.ChangeEvent<{ value: string }>
  ) => {
    // console.log(event);
    // if (event === 13) {
    //   console.log(event);
    // }
    this.setState({
      task: event.target?.value,
    });
  };

  public handleKeyUp: React.KeyboardEventHandler<HTMLInputElement> = (
    event: React.KeyboardEvent<{}>
  ) => {
    if (event.keyCode === 13) {
      (this.props as any).putData(this.state.task);
      this.setState({
        task: '',
      });
    }
  };

  render(): React.ReactElement {
    return (
      <div>
        <input
          type="text"
          value={this.state.task}
          onChange={this.handleChange}
          onKeyUp={this.handleKeyUp}
        />
      </div>
    );
  }
}

export default connect(null, mapDispatchToProps)(Form);

相关文章

网友评论

      本文标题:2021-03-25 react redux thunk

      本文链接:https://www.haomeiwen.com/subject/cbqdhltx.html