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