React-redux状态与外部json

时间:2018-05-19 10:19:16

标签: reactjs react-redux redux-saga

我想在JSON文件中列出PostList.js组件中的帖子 我使用react-redux进行状态管理,使用redux-saga来获取json文件

我的组件是Post.js和PostList.js:

Post.js

    const Post = ({ post }) => {
    <li>
       {post}
    </li>
    }
    export default Post

PostList.js

class PostList extends React.Component {
componentDidMount() {
    console.log('did mount');
    this.props.fetchPosts();
}
render() {
    return (
        <div>
            <ul>
                {this.state.posts(post => (
                    <Post key={post.id} {...post}  />
                ))}
            </ul>
        </div>
    )
}
}

export default PostList

减速

export default (state = [], action) => {
switch (action.type) {
    case "FETCH_POSTS":
        return {
            ...state,
            loading: true,
            posts: []
        }
    case "FETCH_FAILD": 
        return {
            ...state,
            loading: false,
            posts: []
        }
    case "FETCH_SUCCESS":
        return Object.assign({}, state, {
            posts: action.posts
        })
    default:
        return state;
}
}

Actions.js

export const fetchPosts = () => {
  return {
    type: 'FETCH_POSTS'
  }
}

export const fetchSuccess = data => ({
    type: "FETCH_SUCCESS",
    posts: data
})


export const fetchFaild = () => {
    return {
        type: 'FETCH_FAILD'
    }
}

GetPosts.js(容器)

import  { connect } from 'react-redux'
import { bindActionCreators } from 'redux'

import PostList from '../components/PostList'

import { fetchPosts } from '../actions'

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

const mapDispatchToProps = dispatch => bindActionCreators({fetchPosts}, dispatch);

const GetPosts = connect(
    mapStateToProps,
    mapDispatchToProps 
)(PostList)

export default GetPosts

Saga.js

export function* fetchProducts() {
try {
    console.log('saga')
    const posts = yield call(api_fetchPost);
    yield put({ type: "FETCH_SUCCESS", posts});
} catch (e) {
    yield put({ type: "FETCH_FAILD", e});
    return;
}
}

export function* watchFetchProducts() {
    yield takeEvery("FETCH_POSTS", fetchProducts)
}

1 个答案:

答案 0 :(得分:0)

您正在从帖子列表组件的状态中提取帖子。 Redux mapStateToProps将redux状态映射到连接组件的props而不是状态

class PostList extends React.Component {
    componentDidMount() {
        console.log('did mount');
        this.props.fetchPosts();
    }
    render() {
        return (
            <div>
                <ul>
                    {this.props.posts && this.props.posts.map(post => {
                        return ( <Post key={post.id} {...post}  /> );
                    })}
                </ul>
            </div>
        )
    }
}

export default PostList

this.state.posts更改为this.props.posts