【问题标题】:mapStateToProps function , targeting id of the post instead of all the postsmapStateToProps 函数,定位帖子的 id 而不是所有帖子
【发布时间】:2018-03-30 20:48:39
【问题描述】:

我有一个 mapStateToProps 函数,我在其中获取帖子(所有帖子),然后在 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] 中获取所有帖子(想象一下,如果有几百个)。

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 函数中的特定帖子,即:state.match.params.id 而不是所有帖子。但不知道正确的实现方式

我是 reactjs 的新手,任何帮助将不胜感激! 谢谢

【问题讨论】:

  • posts 是数组还是对象?
  • @patrick 它是一个对象{}

标签: reactjs react-redux react-router-dom


【解决方案1】:

如何返回单个帖子:

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 我只想补充一点,对 mapStateToProps() 使用箭头函数会使代码更易于阅读:const mapStateToProps = (state) =&gt; ({ post: state.posts[ownProps.match.params.id] });
    • 同意@the_ghost 但我选择不使用它,因为最初的问题是使用 ES5 语法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多