首页 > 解决方案 > 在react redux中接收数据后调用另一个函数内部的函数

问题描述

如果我收到数据,如何在getTodo函数内部调用函数。? -> 调用函数->的预期效果。getTodosif (data) {getTodo ()}click buttongetTodosif (data) {getTodo ()}

我试图getTodo ()在行动中这样称呼:

.then (({data}) => {
       dispatch ({type: GET_TODOS, payload:
         date
       });
     }, () => getTodo ())

此处演示:https ://stackblitz.com/edit/react-iuvdna?file=actions%2Findex.js

行动

import axios from 'axios';

export const GET_TODOS = 'GET_TODOS';
export const GET_TODO = 'GET_TODO';
export const FETCH_FAILURE = 'FETCH_FAILURE';

export const getTodos = () => 
dispatch => {

  return axios({
      url: 'https://jsonplaceholder.typicode.com/todos',
      method: 'GET',
    })
    .then(({data})=> {
      dispatch({type: GET_TODOS, payload:
        data 
      });   
    },() => getTodo())
    .catch(error => {
      console.log(error);

      dispatch({type: FETCH_FAILURE})
    });
};

export const getTodo = () => 
dispatch => {

  return axios({
      url: 'https://jsonplaceholder.typicode.com/todos/1',
      method: 'GET',
    })
    .then(({data})=> {
      dispatch({type: GET_TODO, payload:
        data 
      });   
    })
    .catch(error => {
      console.log(error);

      dispatch({type: FETCH_FAILURE})
    });
};

减速机

import {GET_TODOS, GET_TODO} from '../../actions';

import { combineReducers } from 'redux';

const todos = (state = [], action) => {
  const { type, payload } = action;

  switch (action.type) {
    case 'GET_TODOS':
      return payload;
    default:
      return state;
  }
};

const todo = (state = {}, action) => {
  const { type, payload } = action;

  switch (action.type) {
    case 'GET_TODO':
      return payload;
    default:
      return state;
  }
};


const rootReducer = combineReducers({
  todos, 
  todo
});

export default rootReducer;

待办事项

import React, { Component } from 'react';
import { connect } from 'react-redux';
import {getTodos, clearTodos, getTodo} from '../.././actions';

class Todos extends Component {
  constructor(props){
    super(props);
  }
  render() {
    return (
      <div>
        <button onClick={this.props.getTodos}>Get Todos</button>
        <ul>
          {this.props.todos.map(todo => {
          return <li key={todo.id}>
                    {todo.title}
                </li>
          })}
        </ul>
        {this.props.todo.id}
      </div>
    );
  }
}

const mapStateToProps = state => {
  const { todos, todo } = state;
  return {
    todos, 
    todo
  };
};

const mapDispatchToProps = dispatch => ({
  getTodos: () => dispatch(getTodos()),
  getTodo: () => dispatch(getTodo())
});

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

标签: javascriptreactjsredux

解决方案


推荐阅读