在React本身中,我具有函数getTodos(),其中它调用了另一个函数getTodo()。它将res.data[0].id传递给getTodo()函数。

反应

此处演示:https://stackblitz.com/edit/react-qvsjrz

代码如下:

class App extends Component {
  constructor() {
    super();
    this.state = {
      todos: [],
      todo: {}
    };
  }

  componentDidMount() {
    this.getTodos()
  }

  getTodos = () => {
    axios({
        url: 'https://jsonplaceholder.typicode.com/todos',
        method: 'GET'
    })
    .then(res => {
      this.setState({
        todos: res.data,
      }, () => this.getTodo(res.data[0].id))
    })
    .catch(error => {
      console.log(error);
    });
  };

  getTodo = (todoId) => {
    axios({
      url: `https://jsonplaceholder.typicode.com/todos/${todoId}`,
      method: 'GET'
    })
    .then(res => {
      this.setState({
        todo: res.data
      })
    })
    .catch(error => {
      console.log(error);

    })
  }

  render() {
    console.log(this.state.todo);
    return (
      <div>

      </div>
    );
  }
}


上面的代码尝试转换为react + redux。

React + Redux

在动作中,我声明了两个函数getTodogetTodos。有人可以建议我如何通过传递getTodo id函数在getTodos函数中调用getTodo函数吗?

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

行动

   import axios from 'axios';

    export const GET_TODOS = 'GET_TODOS';
    export const FETCH_SUCCESS = 'FETCH_SUCCESS';
    export const FETCH_FAILURE = 'FETCH_FAILURE';

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

  return axios({
      url: 'https://jsonplaceholder.typicode.com/todos',
      method: 'GET',
    })
    .then(({data})=> {
      console.log(data);

      dispatch({type: GET_TODOS, payload:{
        data
      }});
    })
    .catch(error => {
      console.log(error);

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

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


  return axios({
      url: 'https://jsonplaceholder.typicode.com/todos',
      method: 'GET',
    })
    .then(({data})=> {
      console.log(data);

      dispatch({type: GET_TODOS, payload:{
        data
      }});
    })
    .catch(error => {
      console.log(error);

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


托多斯

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

class Todos extends Component {
  componentDidMount() {
    this.props.getTodos();
  }

  render() {
    return (
      <ul>
        {this.props.todos.map(todo => {
        return <li key={todo.id}>
                  {todo.title}
               </li>
         })}
      </ul>
    );
  }
}

const mapStateToProps = state => {
  console.log(state.todos);
  const { todos } = state;

  return {
    todos
  };
};

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

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


减速器

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

const initialState = {
  todos: []
};

const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'GET_TODOS':
      return {
        ...state,
        todos: action.payload.data
      };

    default:
      return state;
  }
};

export default rootReducer;


商店

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

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

export default store;

最佳答案

您应该为不同的API使用不同的操作类型,而不是使操作过于复杂。


GET_TODOS-对于/ todos API
GET_TO-对于/ todos / API


要添加具有ID的getTodo方法,这就是我解决的方法-


对于每个li标记,添加一个调用您的onClick API的getTodo。 (这是为了在工作流程中添加getTodo的示例。


    return <li key={todo.id} onClick={() => this.handleClick(todo.id)}>



添加handleClick从道具调用getTodo方法。


首先在组件getTodo中添加mapDispatchToProps



    import { getTodo, getTodos} from '../.././actions';

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



添加handleClick-



  handleClick = id => {
    this.props.getTodo(id).then(() => {
      console.log(`You Clicked: ${JSON.stringify(this.props.todo)}`)
    })
  }



更新您的getTodo操作以将ID作为输入:



  注意:添加的GET_TODO类型


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

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

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




将减速器分为todostodo并使用combineReducers包中的redux-



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

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

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

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

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



运行该应用程序,然后单击待办事项列表中的任何项目。当获取该ID的API响应时,将显示单击的待办事项的控制台日志。


实时沙箱位于此处-https://stackblitz.com/edit/react-ndkasm

09-12 07:27