我正在从自己的操作中检索帖子,并且帖子未显示在
中console.log(this.props.posts)
无论如何,它确实会显示在console.log
动作下
相反,我明白了
理想情况是在posts:Array中显示 Array(2)。因此看来redux不会更新initialState posts
数组,因此无法检索帖子。将action.data.data
更改为action.data
不会有任何改变。
actions.js
export const GetPosts = () => {
return (dispatch, getState) => {
return Axios.get('/api/posts/myPosts')
.then( (res) => {
const data = {
data: res.data
}
console.log(data); // logs data and i can see an array
dispatch({type: GET_POSTS, data })
})
}
}
因此,我更新了状态,以便能够在组件中检索它。
posts.js
import { POST_FAIL, GET_POSTS, POST_SUCC, DELETE_POST} from '../actions/';
const initialState = {
post: [],
postError: null,
posts:[]
}
export default (state = initialState, action) => {
switch (action.type) {
case POST_SUCC:
return ({
...state,
post:action.post
});
case POST_FAIL:
return({
...state,
postError: action.err.response.data
})
case GET_POSTS:
// console.log(action.data.data)
return {...state, posts: action.data.data}
// case DELETE_POST:
// return ({
// ...state,
// posts: action.posts.filter(post => post.id !== action.posts[0].id)
// })
default:
return state
}
}
Posts.js
import React, { Component } from 'react';
import PostList from './PostList';
import Axios from '../Axios';
import {connect} from 'react-redux';
import { withRouter, Redirect} from 'react-router-dom';
import {DeletePost, GetPosts} from '../actions/';
const Styles = {
myPaper:{
margin: '20px 0px',
padding:'20px'
}
,
wrapper:{
padding:'0px 60px'
}
}
class Posts extends Component {
state = {
posts: [],
loading: true,
}
componentWillMount(){
this.props.GetPosts();
// renders an empty posts array
console.log(this.props.posts);
}
onDelete = (id) => {
Axios.post(`/api/posts/delete/${id}`);
this.setState({
posts: this.state.posts.filter(post => post.id !== id)
})
}
render() {
const {loading, posts} = this.state;
if (!this.props.isAuthenticated) {
return (<Redirect to='/signIn' />);
}
if(loading){
return "loading..."
}
return (
<div className="App" style={Styles.wrapper}>
<h1> Posts </h1>
{/* <PostList posts={this.props.posts}/> */}
</div>
);
}
}
const mapStateToProps = (state) => ({
isAuthenticated: state.user.isAuthenticated,
// i know i have to use state.post.posts but i wanted to get an idea if the
// initialize state updated at all
posts: state.post
})
const mapDispatchToProps = (dispatch, state) => ({
// newPost: (post) => dispatch(newPost(post)),
// DeletePost: (id) => dispatch( DeletePost(id))
GetPosts: () => dispatch( GetPosts())
});
export default withRouter(connect(mapStateToProps,mapDispatchToProps)(Posts));
答案 0 :(得分:1)
您的reducer正在设置posts
状态属性:
case GET_POSTS:
// console.log(action.data.data)
return {...state, posts: action.data.data}
您的组件正在将post
状态属性映射到组件的posts
属性:
const mapStateToProps = (state) => ({
isAuthenticated: state.user.isAuthenticated,
// i know i have to use state.post.posts but i wanted to get an idea if the
// initialize state updated at all
posts: state.post
})