在reducer中的http请求后反应更新状态

时间:2019-05-08 01:58:44

标签: javascript reactjs

我正在创建一个React应用程序,该应用程序会接收初始的虚假数据并在组件中进行渲染,现在我正尝试从JSON Placeolder服务中获取数据并在同一组件中进行渲染。

我可以成功获取数据,但是我不知道如何通过化简函数更新组件状态。

我的减速器功能

import axios from "axios";
const initState ={
  projects:[
    {id:1, title:'First project', author:'xyz', dateCreated:'3rd September, 2AM', content:'Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum blanditiis vel eius consequuntur facere sequi, iusto, aspernatur harum a adipisci voluptatum itaque quod nesciunt, officia aliquam placeat tempora laborum? Provident!'},
    {id:2, title:'Second project', author:'abx', dateCreated:'3rd September, 2AM',content:'Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum blanditiis vel eius consequuntur facere sequi, iusto, aspernatur harum a adipisci voluptatum itaque quod nesciunt, officia aliquam placeat tempora laborum? Provident!'},
    {id:3, title:'Third project', author:'juq', dateCreated:'3rd September, 2AM', content:'Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum blanditiis vel eius consequuntur facere sequi, iusto, aspernatur harum a adipisci voluptatum itaque quod nesciunt, officia aliquam placeat tempora laborum? Provident!'}
  ]
}
const ProjectReducer = (state = initState, action) => {
  switch (action.type) {
    case 'CREATE_PROJECT':
    {
      console.log("Project creatred");
      break;
    }
    case 'GET_ALL_PROJECTS':
    {
        axios.get('https://jsonplaceholder.typicode.com/posts')
        .then((response)=>
        {
          state = response.data;
          return state
          console.log(state, action);
          //dispatch({type:'GET_ALL_PROJECTS_RECEIVED', data:response.data});
          
          //I have to call render component from here becuase state now has data.
        })
      //}
    }
    case 'GET_ALL_PROJECTS_RECEIVED':
    {
      return state;
    }
    default:
      break;
  }
  
  return state
}

export default ProjectReducer

index.js文件

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import RootReducer from "./store/reducers/rootReducer";
import thunk from 'redux-thunk';

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

ReactDOM.render(<Provider store={store}><App /></Provider> , document.getElementById('root'));
store.dispatch({type:'GET_ALL_PROJECTS'});
serviceWorker.unregister();

我在其中获取数据并将其传递给另一个组件以呈现它的dshboard组件,该代码在第一次加载组件时被调用,但是在http请求完成后不会执行。

import React, {Component } from "react";
import Notifications from "./notifications";
import ProjectList from "../projects/projectList";
import { connect } from "react-redux";

class Dashboard extends Component
{
    render()
    {
        return(
            <div className="dahboard container">
                <div className="row">
                    <div className="col s12 m6">
                        <ProjectList projects={this.props.projects}></ProjectList>
                    </div>
                    <div className="col s12 m5 offset-m1">
                        <Notifications></Notifications>
                    </div>
                </div>
            </div>
        )
    }
}


const mapStateToProps = (state) => {
  return {
      projects:state.projectRepo.projects
  }
}

const mapDispatchToProps = {
  
}


export default connect(mapStateToProps)( Dashboard)

我可以看到3个经过硬编码的项目条目,但是看不到通过http请求呈现的任何数据。

1 个答案:

答案 0 :(得分:0)

Reducer不是调用API的正确位置,您需要在组件中调用API,然后调用带有响应的操作以更新状态。

减速器代码。



const initState ={
  projects:[
    {id:1, title:'First project', author:'xyz', dateCreated:'3rd September, 2AM', content:'Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum blanditiis vel eius consequuntur facere sequi, iusto, aspernatur harum a adipisci voluptatum itaque quod nesciunt, officia aliquam placeat tempora laborum? Provident!'},
    {id:2, title:'Second project', author:'abx', dateCreated:'3rd September, 2AM',content:'Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum blanditiis vel eius consequuntur facere sequi, iusto, aspernatur harum a adipisci voluptatum itaque quod nesciunt, officia aliquam placeat tempora laborum? Provident!'},
    {id:3, title:'Third project', author:'juq', dateCreated:'3rd September, 2AM', content:'Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum blanditiis vel eius consequuntur facere sequi, iusto, aspernatur harum a adipisci voluptatum itaque quod nesciunt, officia aliquam placeat tempora laborum? Provident!'}
  ]
}
const ProjectReducer = (state = initState, action) => {
  switch (action.type) {
    case 'CREATE_PROJECT':
    {
      console.log("Project creatred");
      break;
    }
    case 'GET_ALL_PROJECTS':
    {
        return { ...state, projects: action.payload };
    }
    case 'GET_ALL_PROJECTS_RECEIVED':
    {
      return state;
    }
    default:
      break;
  }

  return state
}

export default ProjectReducer

组件

import React, {Component } from "react";
import axios from "axios";
import Notifications from "./notifications";
import ProjectList from "../projects/projectList";
import { connect } from "react-redux";

class Dashboard extends Component
{
componentDidMount() {
  this.getProjects();
}
getProjects = () => {
  axios.get('https://jsonplaceholder.typicode.com/posts')
  .then((response)=>
    {
      this.props.dispatch({type:'GET_ALL_PROJECTS_RECEIVED', payload:response.data});
    })
}
    render()
    {
        return(
            <div className="dahboard container">
                <div className="row">
                    <div className="col s12 m6">
                        <ProjectList projects={this.props.projects}></ProjectList>
                    </div>
                    <div className="col s12 m5 offset-m1">
                        <Notifications></Notifications>
                    </div>
                </div>
            </div>
        )
    }
}


const mapStateToProps = (state) => {
  return {
      projects:state.projectRepo.projects
  }
}

const mapDispatchToProps = {

}


export default connect(mapStateToProps)( Dashboard)

希望它会对您有所帮助。