代码之家  ›  专栏  ›  技术社区  ›  Gaurang Shah

使用axios api调用响应redux

  •  1
  • Gaurang Shah  · 技术社区  · 6 年前

    我正在尝试学习react,为此我正在尝试创建一个示例todo应用程序。我有一个python flask后端,它将服务器作为REST服务器,并作为web服务器进行响应。

    一切正常。我可以显示待办事项,也可以删除特定的待办事项。但是现在我已经开始学习Redux了,这看起来真的很混乱。

    我不知道如何调用我的rest服务器。下面只是返回承诺,不确定如何获取数据,而不是承诺。

    store.js

    import axios from 'axios'
    import { createStore } from 'redux'
    
    export const ADD_TODO = 'ADD_TODO'
    
    let nextTodoId = 0
    export const addTodo = text => ({
      type: 'ADD_TODO',
      id: nextTodoId++,
      text
    })
    
    export const listTodo = todos => ({
      type: 'LIST_TODO',
      todos
    })
    
    const add_todo = (id, text) => {
      return axios.post("http://localhost:5001/todos", {id:id, data:text})
        .then(Response=>{
               store.dispatch(addTodo(Response.data));
        })
    }
    
    const fetch_data = () => {
      return axios.get("http://localhost:5001/todos")
            .then(Response=>{
              store.dispatch(listTodo(Response.data))
            })
    }
    const initialState ={
        todos: {},
        new_todo: ''
    }
    
    function todoApp(state = initialState, action) {
        console.log("reducer called...")
        switch (action.type) {
           case ADD_TODO:
            return Object.assign({}, state, {
              new_todo: action.text
            })
          default:
            return state
        }
    }
    
    const store = createStore(todoApp)
    export default store
    

    import React, {Component} from 'react' 
    import {connect} from 'react-redux'
    class App extends Component{
     render(){
      return(        
          <div>
            <button onClick={this.props.addTodo('testing')}>fetch_Data</button>
          </div>
    
       );
     }
    }
    
    export default connect() (App)
    

    index.js

    ReactDOM.render(<Provider store={store}> <App /> </Provider>, 
                    document.getElementById('root'));
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   Hitesh Chaudhari    6 年前

    首先,您应该导出您创建的操作,这些操作随后将被导入,并在使用connect HOC的组件中使用。

    您可以调度“fetch_data”操作以获取组件中的数据。此外,您还可以调度“addTodo”操作以在列表中添加新的todo。

    export const ADD_TODO = 'ADD_TODO';
    export const GET_TODO = 'GET_TODO';
    
    export const fetch_data = () => {
    return (dispatch) => axios.get("http://localhost:5001/todos")
        .then(response => {
             dispatch({type: GET_TODO, todos: response.data});
        })
    }
    
    export const addTodo = text => ({
      type: 'ADD_TODO',
      id: nextTodoId++,
      text: text
    });
    

    const todoApp = (state = initialState, action) => {
    console.log("reducer called...")
    switch (action.type) {
       case ADD_TODO:
          const todos = {...state.todos};
          todos[action.id] = action.text;
          return Object.assign({}, state, {
            todos: todos
          });
       case GET_TODO:
          return Object.assign({}, state, {
            todos: action.todos
          });
       default:
          return state
       }
    }
    

    导入操作,然后调用您在“mapDispatchToProps”中添加的函数来分派操作。

    import React, {Component} from 'react'
    import {connect} from 'react-redux';
    import { addTodo, fetch_data } from "../store";
    class App extends Component{
        render(){
            return(
                <div>
                    <button onClick={this.props.addTodo(todoId, 'testing')}>fetch_Data</button>
                </div>
    
            );
        }
    }
    
    const mapStateToProps = (state) => ({
        todos: state.todoApp.todos
    });
    
    const mapDispatchToProps = (dispatch) => ({
        addTodo: (id, text) => dispatch(addTodo(id, text)),
        fetch_data: () => dispatch(fetch_data())
    });
    
    export default connect(mapStateToProps, mapDispatchToProps)(App);
    
        2
  •  0
  •   KJ. Estevez    6 年前

    redux基于操作和减缩器,基本上减缩器是纯函数,这意味着没有副作用,例如api调用,我建议您阅读更多关于redux的内容,以及如何使用redux和redux块进行api调用

        3
  •  0
  •   Anil Kumar    6 年前

    你是这样做的。您需要在收到响应时发送操作。

    const fetch_data = () => {
      return axios.get("http://localhost:5001/todos")
        .then(Response=>{
               store.dispatch(addTodo(Response.data));
        })
    }
    
    export const addTodo = text => ({
      type: 'ADD_TODO',
      id: nextTodoId++,
      text: text
    })