【问题标题】:getting null and actual result from fetching an API in react通过在反应中获取 API 获得空值和实际结果
【发布时间】:2019-09-06 04:59:35
【问题描述】:

我尝试从 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,然后是实际的虚拟数据。

【问题讨论】:

  • 我认为问题出在mapStateToProps。应该是state.REDUCER. forumPosts你可以在回来之前尝试做一个console.log(state)看看你的结构!
  • 您好,Tobi,是的,我确实尝试过 console.log(state),它给了我两个对象之前的 null 空状态和一个在帖子下载完成后的对象
  • 是的,但是对象有键吗?点赞状态:{postReducer: null}{postReducer: {forumPosts: ....}}

标签: reactjs redux


【解决方案1】:

我认为您在 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;

【讨论】:

  • 从技术上讲你是对的。但它只删除实际数据。不是空的。我很感激
猜你喜欢
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-16
相关资源
最近更新 更多