首页 > 解决方案 > 将函数从 pure react 转换为 redux react

问题描述

在纯粹的反应中,我编写了一个我调用的函数componentDidMount ()

  getTasks = (userId, query, statusTask, pageNumber) => {
    let check = {};
    axios({
      url: `/api/v1/beta/${userId}`,
      method: 'GET'
    })
      .then(res => {
        check = res.data;

        if (res.data) {
          this.setState({
            checkRunning: res.data,
            checkRunningId: res.data.id
          });
          this.utilizeTimes(res.data.task_id);
        }
      })
      .catch(error => {
        console.log(error);
      })
      .then(() => {
        const params = {
          sort: 'name'
        };

        if (query) {
          params['filter[qwp]'] = query;
          if (this.state.tasks[0]) {
            this.setState({
              selectedId: this.state.tasks[0].id,
              selectedTabId: this.state.tasks[0].id
            });
          }
        }

        axios({
          url: '/api/v1//tasks',
          method: 'GET',
          params
        })
          .then(res => {
            if (res.status === 200 && res.data) {
              this.setState({
                tasks: res.data,
                lengthArrayTasks: parseInt(res.headers['x-pagination-total-count'])
              });

              if (!check && res.data && res.data[0]) {
                this.setState({
                  selectedTabId: res.data[0].id,
                });

                this.load(res.data[0].id);
              }

              let myArrayTasks = [];
              myArrayTasks = res.data;
              let findObject = myArrayTasks.find(task => task.id === this.state.runningTimerTask.id);

              if (
                !findObject &&
                this.state.runningTimerTask &&
                this.state.runningTimerTask.id &&
                this.state.query === ''
              ) {
                this.setState({
                  tasks: [this.state.runningTimerTask, ...myArrayTasks]
                });
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      });
  };

我正在尝试将其重写为 redux,但效果不佳。首先它发出一个请求/ api / v1 / beta / $ {userId},将答案写入变量中checkcheck传递到下一个then。在接下来then执行请求'/api/v1//tasks' 有人可以帮帮我吗?我要求一些提示。这有点复杂吗?

到目前为止,我已经设法创建了这样的东西:

店铺

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';

const store = createStore(rootReducer, applyMiddleware(thunk));

export default store;

行动

export const RUNNING_TIMER = 'RUNNING_TIMER';
export const GET_TASKS = 'GET_TASKS';
export const FETCH_FAILURE = 'FETCH_FAILURE';

export const runningTimer = (userId, query, statusTask, pageNumber) => dispatch => {
  console.log(userId);
  axios({
    url: `/api/v1/beta/${userId}`,
    method: 'GET'
  })
    .then(({ data }) => {
      dispatch({
        type: RUNNING_TIMER,
        payload: data
      });
    })
    .catch(error => {
      console.log(error);

      dispatch({ type: FETCH_FAILURE });
    })
    .then(() => {
      const params = {
        sort: 'name'
      };

      axios({
        url: '/api/v1//tasks',
        method: 'GET',
        params
      })
        .then(({ data }) => {
            dispatch({
                type: GET_TASKS,
                payload: data
            });
        })
        .catch(error => {
            console.log(error);
        });
    });
};

减速器

import { RUNNING_TIMER, GET_TASKS } from '../actions';

const isRunningTimer = (state = {}, action) => {
  const { type, payload } = action;
  switch (type) {
    case RUNNING_TIMER:
      return {
        checkRunningTimer: payload,
        checkRunningTimerId: payload && payload.id ? payload.id : null
      };
      break;
      case GET_TASKS:
      return {
        tasks: payload,
        lengthArrayTasks: parseInt(action.headers['x-pagination-total-count'])
      };
    default:
      return state;
  }
};

const rootReducer = combineReducers({ isRunningTimer });

export default rootReducer;

应用程序

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  componentDidMount() {
    this.props.runningTimer();
  }

  render() {
    return (
      <div>

      </div>
    );
  }
}

const mapStateToProps = state => {
  const { isRunningTimer } = state;

  return {
    isRunningTimer
  };
};

const mapDispatchToProps = dispatch => ({
  runningTimer: (userId, query, statusTask, pageNumber) => dispatch(runningTimer()),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

标签: javascriptreactjsreduxreact-redux

解决方案


1 考虑您的状态设计。

我发现考虑状态对象在给定时间点的样子很有用。

这是我的应用程序中使用的 initialState 示例。

const initialState = {
        grocers: null,
        coords: {
            latitude: 37.785,
            longitude: -122.406
        }

    };

这是在 createStore 中注入的。

分解您的应用程序状态对象/属性也应该有助于您简化操作。

2号

考虑分解你的行为。

我的想法,解耦动作代码,在.then在第二个 .then .(考虑将结果保存在用户的某处:对象)

        .then(response => {
          const data = response.data.user;
          setUsers(data);})
        .catch(error => {
            console.log('There has been a problem with your fetch operation: ' + error.message);
        })

    function setUsers(data){
        dispatch({
            type: FETCH_USERS,
            payload: data
        });
    }

这指的是 SOLID 设计原则中的 S。单一职责原则。

https://devopedia.org/solid-design-principles

3 号

如果“getUser”信息获取失败,请考虑这一点。

分离进程/响应将允许更干净地调试应用程序。例如,用户 api 失败或 getTask api 失败等。


更多关于 redux 的资源。 https://redux.js.org/introduction/learning-resources#thinking-in-redux


推荐阅读