mapStateToProps 函数,针对 post 而不是所有 post 的 id

mapStateToProps function , targeting id of the post instead of all the posts

我有一个 mapStateToProps 函数,我在其中获取 posts(所有 posts),然后在 render() 函数中定位 id

show_posts.js(组件)

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchPost } from '../actions';

class PostsShow extends Component {
    componentDidMount() {

        const { id } = this.props.match.params ; 
        this.props.fetchPost(id);
    }


    render() {

        posts[this.props.match.params.id]; // the post i want to show

        return (
            <div>
            <h3>Title of the Post will be Here</h3>             
            </div>);
    }
}

function mapStateToProps(state) {
    return { posts: state.posts};

}
export default connect(mapStateToProps, {fetchPost})(PostsShow);

而不是在 posts[this.props.match.params.id] 中获取所有 post(想象一下,如果有数百个),我如何传递用户请求的单个 post。

index.js(操作)

import axios from 'axios';

export const FETCH_POST = 'FETCH_POST';

const ROOT_URL = 'http://xxxx.abcac.com/api';
const API_KEY = '?key=xxxxxxxx';



export function fetchPost(id) {
    const request = axios.get(`${ROOT_URL}/posts/${id}${API_KEY}`);

    return {
        type: FETCH_POST,
        payload: request
    };

}

在我看来,我们可以针对 mapStateToProps 函数中的特定 post,即:state.match.params.id 而不是所有 post。但是不知道正确的实现方式

我是 reactjs 的新手,我们将不胜感激! 谢谢

mapStateToProps 采用第二个参数,通常写为 ownProps。那是已经传递给它正在连接的组件的道具。您可以在 react-redux docs

中阅读相关内容

以下是我将如何实现您的要求:

function mapStateToProps(state, ownProps) {
    const postId = ownProps.match.params.id;
    const post = state.posts[postId];

    return { 
        post 
    };
}

如何return单人post:

function mapStateToProps({ posts }, ownProps) {
    return { post: posts[ownProps.match.params.id]};
}