从反应中获取API获取空值和实际结果

时间:2019-04-16 06:56:43

标签: reactjs redux

我试图做一些反应从typicode.com提取api,但是以某种方式返回了2组道具。一个为空,另一个为实际数据。

我尝试删除化简器中的初始状态。 我已将调用从componentDidMount生命周期挂钩移至componentWillMount()。

我一直在使用redux thunk中间件。

这些是减速器:

const initialState =[{}]

const postReducer = (state=initialState , action) =>{


    switch(action.type){

        case "FETCH_POST":
            return { ...state, forumPosts:action.payload};

        default:
            return state;

    }
}

export default postReducer;

这些是动作:

import axios from 'axios';


export const fetchPosts = ()=>dispatch =>{
        axios.get(`https://jsonplaceholder.typicode.com/posts`)
        .then(res =>(
        dispatch({type: "FETCH_POST", payload:res.data }) 
    )
    )
    .catch(err => dispatch({type: "FETCH_POST", payload : {}}))


}

这些是主要应用程序:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { connect } from 'react-redux';
import  {fetchPosts} from './actions/postActions'


class App extends Component {
  componentWillMount(){
    this.props.fetchPosts();    
  }
  render() {
     const {forumPosts } = this.props;
     console.log(forumPosts)

    return (


      <div className="App">

      </div>
    )

  }
}

const mapStateToProps = (state) =>{
  return{
    forumPosts : state.forumPosts 
  }
};



export default connect(mapStateToProps, {fetchPosts})(App);

这是商店:

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

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

预期结果是来自typicode的虚拟帖子列表,但它首先返回null,然后返回实际的虚拟数据。

1 个答案:

答案 0 :(得分:0)

我认为您在reducer中犯了错误,因为我可以看到您期望对象数组为posts,并且您正在使用带对象而不是数组的散布运算符,请尝试这样做将解决您的问题,

const initialState = [{}];

const forumPosts = (state = initialState , action) => {


    switch(action.type) {

        case "FETCH_POST":
            return  [ ...state, ...action.payload ]; // merging 2 arrays using spread oprator

        default:
            return state;

    }
}

export default forumPosts;