【发布时间】: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: ....}}